[英]How many activities should I use with a bottom navigation bar?
我是android studio的新手,將不勝感激。
我已經在MainActivity中以編程方式設置了底部導航欄。 我想知道-與其他片段一起設置的最佳方法是什么。 我有三個片段,一個用於導航欄中的每個選項卡,其他的片段可以在從導航欄片段中按下按鈕時打開。
我的問題是,在連接連接到導航欄的片段的同一活動中或在其他活動中,我應在哪里設置這些其他片段。
如何保存顯示的片段的當前狀態,以便當我移至其他選項卡然后向后移動時,其狀態與離開時相同。
我的問題是,這些其他片段應在哪里設置? 在連接連接到導航欄的片段的同一活動中或在另一活動中。
這取決於您以及如何顯示片段。 您可以在同一活動中顯示它們或打開另一個活動。 但是請記住,如果打開另一個活動,則將丟失上一個活動的導航欄(一個活動始終使用整個屏幕)
FragmentManager和FragmentTransaction到底做什么?
如何保存顯示的片段的當前狀態,以便當我移至其他選項卡然后向后移動時,其狀態將與離開時的狀態相同?
在https://developer.android.com/guide/components/fragments.html#Lifecycle上了解片段生命周期
具體來說,您想將狀態保存在onSaveInstanceState
,並且在onCreate
重新創建片段時,保存的內容將發送回給您。
我想進一步說明@rupps所說的內容,因為我覺得FragmentManager / Transaction的作用所在並沒有從您期望的地方得到。
我假設您正在使用BottomNavigationView 。
不管Fragment的(重要)生命周期如何,您都必須了解Fragment 總是附加到活動中(請注意:這不是真的,但現在不談論無頭的片段)。
您可以采用的方法是,“活動”布局如下所示:(使用偽代碼)
<RelativeLayout width=match_parent height=match_parent>
<FrameLayout
id="@+id/your_fragment_container"
width=match_parent
height=match_parent
layout_above="@+id/navbar" />
<BottomNavigationView
id="@id/navbar"
width=match_parent
height=wrap_content
align_parent_bottom=true />
</RelativeLayout>
這樣,BottomNavBar將始終出現在布局的底部。
現在您需要處理片段到那里了……假設您需要在該欄上附加一個偵聽器 ,並且當收到一個回調消息,表明已選擇了一個新的菜單項時…您可以繼續更改片段(您將始終啟動時發生一個事件,或者您可以在onCreate期間強制執行它)。
您將在字面上將switch / if語句添加到onNavigationItemSelected(MenuItem item)
方法。
並調用addFragment(TAG);
視case
而定。
偽代碼讓您了解:
private void addFragment(final String tag) {
final Fragment existing = getSupportFragmentManager().findFragmentByTag(tag);
if (existing == null) {
final Fragment newInstance = getNewFragmentInstanceWithTag(tag);
getSupportFragmentManager()
.beginTransaction()
.replace(getFragmentContainerLayout(), newInstance, tag)
.commit();
}
}
您還需要提供:
private int getFragmentContainerLayout() {
return R.id.your_fragment_container;
}
和…
public static final String TAB1_TAG = "TAB1_TAG";
public static final String TAB2_TAG = "TAB2_TAG";
public static final String TAB3_TAG = "TAB3_TAG";
protected Fragment getNewFragmentInstanceWithTag(String tag) {
switch (tag) {
case TAB1_TAG:
return Tab1Fragment.newInstance();
case TAB2_TAG:
return Tab2Fragment.newInstance();
case TAB3_TAG:
return Tab3Fragment.newInstance();
default:
return null;
}
}
那么,FragmentManager / Transaction是什么青蛙呢?
可以將Manager視為一個單例對象(每個應用程序一個),該對象保留對您的Fragments的引用,並可以為您檢索Fragments(如果以前存在)。 它處理事務(添加/刪除/隱藏/顯示等),因此您以后可以回滾它們(例如,在事務中添加片段,如果還添加了addToBackStack()
則可以簡單地告訴Manager:彈出最后一個事務,有效地回滾。
這是一個怪物。 它有超過9000年的錯誤,而且不是很直觀。 但是一旦習慣了,就可以“使用”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.