0

What is the best practice to highlight the right menu item in a BottomNavigationView after coming back to that Activity?

My Scenario: a MainActivity with a bottomNavigation which switches between fragments and starts other Activities. The Activities started from that menu have android:parentActivityName=".activities.MainActivity" set in the manifest file. A click on the back button in the top bar brings me back to the right Activity and the last visited Fragment in this Activity is shown too, since I have added android:launchMode="singleTop" for the MainActivity. BUT always the first menu item is highlighted

My workaround at the moment is to add the following code to every Fragment (not very nice)

@Override
public void onResume() {
    super.onResume();
    BottomNavigationView navigation = (BottomNavigationView) getActivity().findViewById(R.id.navigation);
    Menu menu = navigation.getMenu();
    for (int i = 0; i < menu.size() ; i++) {
        menu.getItem(i).setChecked(false);
    }
    menu.getItem(MENU_ITEM_POS).setChecked(true);
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
trayan.dev
  • 87
  • 4
  • You can use SharedPreference to save and load selected position. I would also say you can use `onSaveInstance()` method but i suppose it does not work if launch mode is single top. – Thracian Oct 20 '17 at 11:44
  • You ca try saving two positions. One of the current one (your `MENU_ITEM_POS`) and the PREVIOUS one (`PREVIOUS_MENU_ITEM_POS`). This way you wont need a loop. – Ellisan Oct 20 '17 at 11:45
  • Duplicate: https://stackoverflow.com/questions/41744219/how-to-highlight-the-item-when-pressed-using-bottomnavigationview-between-activi?rq=1 – lhilbert Feb 28 '20 at 14:08

0 Answers0