Keep Selected Navigation Orientation Changes
I have implemented for Android 3+ devices view navigation via ActionBar NavigationMode (DROP_DOWN_LIST).
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
SpinnerAdapter mSpinnerAdapter = ArrayAdapter.createFromResource(this, R.array.action_list, android.R.layout.simple_spinner_dropdown_item);
getActionBar().setListNavigationCallbacks(mSpinnerAdapter, new OnNavigationListener() {
@Override
public boolean onNavigationItemSelected(int index, long arg1) {
if(index == 0)
selectHomeView();
else
selectMainView();
return true;
}
});
This works as intended, but when the orientation changes, onNavigationItemSelected is called again with index = 0, returning my activity to the first view.
How can I keep this state? And don't let onNavigationItem be called at index 0 onCreate?
EDIT:
Following Kirill's answer, it is possible to keep the current inedx, but there is a third view that cannot be selected using the NavigationList, and if I don't call setNavigationItemSelected after onCreate, it automatically fires with index = 0, returning the application to the first view.
It is my problem.
source to share
You can extend the following function to be subtracted whenever the activity state might be lost,
@Override
protected void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save the state of the drop down menu
savedInstanceState.putInt("selectedIndex",mDropMenu.getSelectedIndex());
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
super.onRestoreInstanceState(savedInstanceState);
// Restore the state of the drop down menu
mDropMenu.setSelectedIndex(savedInstanceState.getInt("selectedIndex"));
}
note that the mDropMenu must be replaced with your object and you must use the appropriate method on it
source to share