Problem: Due to the lack of real state, the platform uses minimized navigation (i.e. Spinner). The system automatically determines NAVIGATION_MODE_TABS for the landscape and NAVIGATION_MODE_LIST for the portrait, changing the orientation from landscape to portrait, updates the user interface, but for some reason does not update the navigation mode property to NAVIGATION_MODE_LIST, and therefore mActionView.setDropdownSelectedPosition is not called (position). See the following ActionBarImpl code: setSelectedNavigationItem
public void setSelectedNavigationItem(int position) { switch (mActionView.getNavigationMode()) { case NAVIGATION_MODE_TABS: selectTab(mTabs.get(position)); break; case NAVIGATION_MODE_LIST: mActionView.setDropdownSelectedPosition(position); break; default: throw new IllegalStateException( "setSelectedNavigationIndex not valid for current navigation mode"); } }
Workaround: Through reflection, we can get the spinner tab object and call the setSelection method.
private Spinner getTabSpinner() { try { int id = getResources().getIdentifier("action_bar", "id", "android"); View actionBarView = findViewById(id); Class<?> actionBarViewClass = actionBarView.getClass(); Field mTabScrollViewField = actionBarViewClass.getDeclaredField("mTabScrollView"); mTabScrollViewField.setAccessible(true); Object mTabScrollView = mTabScrollViewField.get(actionBarView); if (mTabScrollView == null) { return null; } Field mTabSpinnerField = mTabScrollView.getClass().getDeclaredField("mTabSpinner"); mTabSpinnerField.setAccessible(true); Object mTabSpinner = mTabSpinnerField.get(mTabScrollView); if (mTabSpinner != null) { return (Spinner)mTabSpinner; } } catch (Exception e) { return null; } return null; }
Then call the above method in the onPageSelected event.
public void onPageSelected(int position) { actionBar.setSelectedNavigationItem(position); Spinner spinner = getTabSpinner(); if (spinner != null) { spinner.setSelection(position); } }
Wrote this post https://gist.github.com/2657485
source share