Using ASL's 25.0 BottomNavigationView
i'm faced with some troubles, like a save selected item (or his index) and selected item programmatically.
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:
Lets wait until ASL devs fix this.
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 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 menuprivate 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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With