Using ASL's 25.0 BottomNavigationView
i'm faced with some troubles, like a save selected item (or his index) and selected item programmatically.
问题:
回答1:
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.
回答2:
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.
回答3:
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();
}
回答4:
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.