Save Bottom Navigation Selected item while rotating the screen

Using ASL 25.0 BottomNavigationView , I encounter some problems, such as saving the selected item (or its index) and the selected item programmatically.

+7
android android-support-library android-support-design
source share
4 answers

Unfortunately, at this point there are many features that are not available in the BottomNavigationView .

Your question was really interesting, and I wrote this advanced BottomNavigationView that saves the state and in your case saves the last selected item.

Here is the gist for the code

This extension includes:

  • Provides two publicly available methods for setting and retrieving selected items programmatically.
  • Saves and restores state only for the last selection.

Wait for ASL devs to fix this .

+5
source share

I work with BottomNavigationView and here is the code that the application works with when rotating the screen. First, I created a variable to store the identifier of the selected menu
private int saveState;

Saving id value using the selected menu identifier in a variable

  @Override protected void onResume() { super.onResume(); navigation.setSelectedItemId(saveState); } @Override public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) { super.onSaveInstanceState(outState, outPersistentState); saveState = navigation.getSelectedItemId(); } 

Then, the onCreate method retrieves the id value, if available.

  if(savedInstanceState!=null){ navigation.setSelectedItemId(saveState); }else{ FragmentTransaction transaction = getSupportFragmentManager().beginTransaction(); transaction.replace(R.id.content, MapFragment.newInstance()); transaction.commit(); } 
+2
source share

Agree with Nikolai!

I created my own gist too

To save the state after rotation, you need to add Activity to it:

 @Override protected void onSaveInstanceState(Bundle outState) { outState.putInt("opened_fragment", bottomNavigation.getCurrentItem()); super.onSaveInstanceState(outState); } 

and in onCreate , right after setting up BottomNavigationView :

 final defaultPosition = 0; final int bottomNavigationPosition = savedInstanceState == null ? defaultPosition : savedInstanceState.getInt("opened_fragment", defaultPosition); bottomNavigation.setCurrentItem(bottomNavigationPosition); 

The biggest plus of this proposition is: There are several types of listeners; this shows that the previous position of choice and the listeners react even when the position is set programmatically. Everything is written in the link, use if you need.

+1
source share

I had the same problem and I upgraded from 25.0.1 to 25.3.1 and it started working correctly, without the need for additional code, you can check the support library support website for the latest version.

Hope this helps.

0
source share

All Articles