Save BottomNavigationView selected item during screen rotation

╄→尐↘猪︶ㄣ 提交于 2019-12-01 03:14:48

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.

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();
        }
Boris Safonov

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.

I was having the same problem and what I did was to update from 25.0.1 to 25.3.1 and it started working correctly without the need of no additional code. You can check the Support Library Revision website for the latest version.

I hope it helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!