![](/img/trans.png)
[英]How to change bottom navigation icon color if I change Fragment programmatically
[英]How to change bottom app bar navigation icon programmatically
我正在制作一個有一個活動和許多片段的Android應用程序。 該活動包含一個底部應用程序欄,該底部欄中有一個導航圖標。 像這樣:
<com.google.android.material.bottomappbar.BottomAppBar
android:id="@+id/bottom_appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
app:backgroundTint="@color/colorbottomappbar"
app:fabAlignmentMode="center"
app:navigationIcon="@drawable/ic_menu_green_24dp">
</com.google.android.material.bottomappbar.BottomAppBar>
該導航菜單圖標將顯示在每個片段中。 但是,在某些片段中,我想將底部應用程序欄中的導航圖標更改為后退按鈕/圖標。 我該如何實現? 另外,目前,我在主活動中處理導航圖標單擊。 如果出現后退圖標,該如何處理點擊? 它如何知道當前片段是什么,以及如何確定后退圖標導致的片段?
如果查看文檔 ,您會發現BottomAppBar
從Toolbar
擴展而來,它具有一個名為setNavigationIcon(int res)
的繼承方法。
您可以實現主要Activity實現的接口,如下所示:
interface FramentChangedListener {
void onFragmentChanged(int type);
}
您的活動將執行以下操作:
public class MainActivity extends Activity implements FragmentChangedListener {
// This will keep track of what is currently shown
private int current = 0;
@Override
public void onFragmentChanged(int type) {
if (type == FirstFragment.SOME_TYPE) {
// Update the current fragment value, we're associating each fragment
// with an int value.
current = type;
bottomAppBar.setNavigationIcon(R.drawable.your_back_icon);
}
}
...
}
在您的片段中,您將執行以下操作:
public class FirstFragment extends Fragment {
private FragmentChangedListener listener;
public static final int SOME_TYPE = 1;
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceOf FragmentChangedListener) {
// context in this case is your activity, which implements FragmentChangedListener
listener = (FragmentChangedListener) context;
// You can call the listener now
listener.onFragmentChanged(SOME_TYPE);
}
}
}
在您的“活動”中,通過setNavigationOnClickListener
將偵聽器添加到BottomAppBar,並且每當收到導航圖標事件時,您都可以檢查我們定義的current
值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.