I'm trying to fix the issue with restarting activity on orientation changes.
I have an ActionBar
with drop-down list navigation and after every rotation first element of this list is being activated. Keeping fragment
content wasn't difficult, but I don't know how to set active list item.
Here is the definition of ActionBar
:
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
ArrayAdapter<CharSequence> list = ArrayAdapter
.createFromResource(this, R.array.action_list, android.R.layout.simple_dropdown_item_1line);
list.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
getActionBar().setListNavigationCallbacks(list, this);
And here is my workaround:
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
if (!application.isRotated) {
application.activePosition = itemPosition;
application.activeId = itemId;
getFragmentManager().beginTransaction()
.replace(android.R.id.content, MyFragment.newInstance(itemPosition))
.commit();
} else {
application.isRotated = false;
this.onNavigationItemSelected(application.activePosition, application.activeId);
}
return true;
}
@Override
protected void onStop() {
super.onStop();
application.isRotated = true;
}
I'm not sure it's the best solution though.
I just found that function. It is setSelectedNavigationItem(int position)
.
Set the selected navigation item in list or tabbed navigation modes.
Example:
actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(adapter, this);
actionBar.setSelectedNavigationItem(position);
As of support library v7, you just need to save / restore the state of the ActionBar:
private static final String STATE_SELECTED_NAVIGATION_ITEM = "selectedNavItem";
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Restore the previously serialized current dropdown position.
if (savedInstanceState.containsKey(STATE_SELECTED_NAVIGATION_ITEM)) {
getSupportActionBar().setSelectedNavigationItem(
savedInstanceState.getInt(STATE_SELECTED_NAVIGATION_ITEM));
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
// Serialize the current dropdown position.
outState.putInt(STATE_SELECTED_NAVIGATION_ITEM, getSupportActionBar()
.getSelectedNavigationIndex());
}
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