I am using the new android.support.design.widget.BottomNavigationView
from the support library.
How can I set the current selection from code? I realized, that the selection is changed back to the first item, after rotating the screen. Of course it would also help, if someone could tell me, how to "save" the current state of the BottomNavigationView
in the onPause
function and how to restore it in onResume
.
Thanks!
From API 25.3.0 it was introduced the method setSelectedItemId(int id)
which lets you mark an item as selected as if it was tapped.
From docs:
Set the selected menu item ID. This behaves the same as tapping on an item.
Code example:
BottomNavigationView bottomNavigationView;
bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottomNavigationView);
bottomNavigationView.setOnNavigationItemSelectedListener(myNavigationItemListener);
bottomNavigationView.setSelectedItemId(R.id.my_menu_item_id);
IMPORTANT
You MUST have already added all items to the menu (in case you do this programmatically) and set the Listener before calling setSelectedItemId(I believe you want the code in your listener to run when you call this method). If you call setSelectedItemId before adding the menu items and setting the listener nothing will happen.