Reputation: 10971
I have an ActionBar with List Navigation mode. The problem is after selecting items from the navigation spinner, when the screen orientation changes the navigation spinner selected index is reset to 0.
How can I preserve the selected index of the spinner during configuration changes ?
Thanks
Upvotes: 4
Views: 4749
Reputation: 1295
You should override onSaveInstanceState
and save selected navigation list position to bundle.
Don't forget to restore position in onCreate
.
Look at example below:
public class MainActivity
{
private static final String CURRENT_FRAGMENT_TAG = "fragmentPosition";
@Inject @Named("navigationFragments")
private Provider<? extends Fragment>[] fragmentProviders;
@Override
protected void onCreate(Bundle bundle)
{
super.onCreate(bundle);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
actionBar.setListNavigationCallbacks(ArrayAdapter.createFromResource(
this, R.array.navigation_menu, android.R.layout.simple_list_item_1), new ActionBar.OnNavigationListener()
{
@Override
public boolean onNavigationItemSelected(int itemPosition, long itemId)
{
final String fragmentTag = "fragment-" + itemPosition;
// to prevent fragment re-selection and loosing early saved state
if (getSupportFragmentManager().findFragmentByTag(fragmentTag) != null)
{
return true;
}
final Fragment fragment = fragmentProviders[itemPosition].get();
getSupportFragmentManager().beginTransaction().
replace(android.R.id.content, fragment, fragmentTag).
commit();
return true;
}
});
actionBar.setSelectedNavigationItem(bundle != null
? bundle.getInt(CURRENT_FRAGMENT_TAG)
: 0);
}
@Override
protected void onSaveInstanceState(Bundle outState)
{
super.onSaveInstanceState(outState);
outState.putInt(CURRENT_FRAGMENT_TAG, getSupportActionBar().getSelectedNavigationIndex());
}
/*
Additional stuff here
*/
}
Provider<? extends Fragment>[] fragmentProviders
is a list of factory method objects which creates new fragment.
Replace getSupportActionBar()
to getActionBar()
and getSupportFragmentManager()
to getFragmentManager()
if you don't use actionbarsherlock
Upvotes: 5