我想用snackbar
在應用程序的任何部分顯示消息。我的意思是當無線網絡被禁用, 應該有一個小吃店說無線網絡禁用。這是在應用程序的任何部分(任何片段或任何活動)確定的。 目前,我在subfragment
中確定了這一點,其中所有片段延伸subfragment
,我也在MainActivity
中使用它。 這工作正常。問題在於協調器佈局爲snackbar
。我如何在每個XML中給這個coordinator layout
? 什麼是最好的解決方案?xml的協調器佈局
1
A
回答
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;
}
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爲你的片段/活動獲得了一個父類,你應該能夠輕鬆地爲你的所有子類創建一些輔助方法。
希望這會有所幫助。
相關問題
- 1. 與協調佈局
- 2. 協調器佈局中的工具欄
- 3. 協調器佈局中的ExpandableListView
- 4. LinearLayout重疊支持協調器佈局
- 5. 相對佈局和協調器佈局之間的佈局問題
- 6. 如何在協調器中垂直放置佈局佈局
- 7. 無法使用協調器佈局以及約束佈局
- 8. 嵌套協調器佈局和應用程序佈局
- 9. Android - 框架佈局高度與協調器佈局不匹配
- 10. ConstraintLayout vs協調員佈局?
- 11. Android協調員佈局
- 12. 協調員佈局 - 佈局縮減不需要的動畫
- 13. 使用協調器佈局在LinearLayout底部添加布局的問題
- 14. 協調器內無限回收器視圖佈局
- 15. 協調佈局不適用於選項卡布局
- 16. Android協調佈局與視差標題線性佈局?
- 17. 協調員佈局與回收+按鈕
- 18. 協調佈局和透明狀態欄
- 19. 頁腳表示協調佈局
- 20. 搜索查看協調佈局
- 21. 谷歌地圖和協調佈局
- 22. Viewpager溢出協調器佈局內的屏幕
- 23. 額外的空間使用協調器佈局,而滾動
- 24. 使用與Firebase協調器佈局的ClassNotFoundException
- 25. 沒有用協調器佈局隱藏的工具欄
- 26. 協調器佈局中的重疊視圖
- 27. Android - 協調器佈局中的滾動和底部表格
- 28. 隱藏協調器佈局內的tablayout,這是外部活動
- 29. ViewPager在協調器佈局中的高度超過可用
- 30. 協調器佈局將內容移動到AppbarLayout的高度
我應該在哪裏添加此代碼? – MagdHo0506
將它添加到你的BaseActivity和BaseFragment中,你也可以使它成爲一個靜態方法,並在你想要顯示小吃店通過當前活動的地方調用它@MagdHo0506 –