Android ActionBar with navigation list: keep selected position position during configuration change?

I have an ActionBar with a list of navigation modes. The problem is that after selecting items from the navigation counter, when the screen orientation changes, the selected navigator rotation index reset is 0.

How to save the selected counter index during configuration changes?

thanks

+4
source share
1 answer

You must override onSaveInstanceState and save the selected position of the navigation list to combine. Remember to restore your position in onCreate .

See an 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 Provider<? extends Fragment>[] fragmentProviders is a list of objects of the factory method that creates a new fragment. Replace getSupportActionBar() with getActionBar() and getSupportFragmentManager() with getFragmentManager() if you are not using actionbarsherlock

+5
source

All Articles