Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save BottomNavigationView selected item during screen rotation

Using ASL's 25.0 BottomNavigationView i'm faced with some troubles, like a save selected item (or his index) and selected item programmatically.

like image 855
Eugene Stepanov Avatar asked Oct 31 '16 21:10

Eugene Stepanov


3 Answers

Unfortunately, there are plenty of features missing in BottomNavigationView at this stage.

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

Here is gist to the code

This extension includes:

  • Gives public two method to set and get selected items programatically.
  • Saves and restores state only for the last selection.

Lets wait until ASL devs fix this.

like image 119
Nikola Despotoski Avatar answered Nov 13 '22 19:11

Nikola Despotoski


Agree with Nikola!

I created my own gist too

To save state after rotation you need add to you Activity:

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

and into onCreate method, just 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 gist is: There are few kinds of listeners, it shows you previous selection position and listeners react even when the position is set programmatically. Everything is written in link, use if you need.

like image 23
borichellow Avatar answered Nov 13 '22 19:11

borichellow


I am working with BottomNavigationView and here is the code with which the app is working correctly on screen rotation. Firstly, I created a variable to hold the id of selected menu
private int saveState;

Saving the value of id by taking the selected menu id in the 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 in the onCreate method retrieving the value of id if available

        if(savedInstanceState!=null){
            navigation.setSelectedItemId(saveState);
        }else{
            FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.content, MapFragment.newInstance());
            transaction.commit();
        }
like image 41
Akshay Nandwana Avatar answered Nov 13 '22 19:11

Akshay Nandwana