2017-02-21 106 views
1

我想用snackbar在應用程序的任何部分顯示消息。我的意思是當無線網絡被禁用, 應該有一個小吃店說無線網絡禁用。這是在應用程序的任何部分(任何片段或任何活動)確定的。 目前,我在subfragment中確定了這一點,其中所有片段延伸subfragment,我也在MainActivity中使用它。 這工作正常。問題在於協調器佈局爲snackbar。我如何在每個XML中給這個coordinator layout? 什麼是最好的解決方案?xml的協調器佈局

回答

2

我認爲常見的方式是遍歷根視圖,並找到孩子是誰的CoordinatorLayout的情況下,代碼段可以是一擊:

public View getCoordinateLayout(Activity activity) { 
    ViewGroup vg = (ViewGroup) activity.findViewById(android.R.id.content); 
    ViewGroup root = (ViewGroup) vg.getChildAt(0); 
    int childCount = root.getChildCount(); 
    for(int i=0;i<childCount;i++){ 
     View view = root.getChildAt(i); 
     if(view instanceof CoordinatorLayout){ 
      return view; 
     } 
    } 
    return null; 
} 
+0

我應該在哪裏添加此代碼? – MagdHo0506

+0

將它添加到你的BaseActivity和BaseFragment中,你也可以使它成爲一個靜態方法,並在你想要顯示小吃店通過當前活動的地方調用它@MagdHo0506 –

2

看起來好像您要爲所有其他佈局使用父級佈局結構。比方說,我們的母公司佈局文件名爲structure.xml,它看起來是這樣的:

<android.support.design.widget.CoordinatorLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <FrameLayout 
     android:id="@+id/container" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" /> 

</android.support.design.widget.CoordinatorLayout> 

然後,當你創建你可以擡高你平時佈局的活動,說activity_main.xml,像這樣:

@Override 
protected void onCreate(Bundle savedInstanceState){ 
    super.onCreate(savedInstanceState); 

    setContentView(R.layout.structure); 
    LayoutInflater.from(this).inflate(R.layout.activity_main, (FrameLayout) findViewById(R.id.container), false); 
} 

每當你創建你平常佈局的片段,說frag_main.xml,你可以做這樣的:

@Override 
public View onCreateView(LayoutInflater inflater, ViewGroup group, Bundle saved) { 
    View view = inflater.inflate(R.layout.structure, group, false); 
    inflater.inflate(R.layout.frag_main, (FrameLayout) view.findViewById(R.id.container), false); 

    return view; 
} 

既然你ALR eady爲你的片段/活動獲得了一個父類,你應該能夠輕鬆地爲你的所有子類創建一些輔助方法。

希望這會有所幫助。