Problem:
Due to an insufficient real-state the platform uses collapsed navigation (i.e. Spinner). The system auto-determines NAVIGATION_MODE_TABS for landscape & NAVIGATION_MODE_LIST for portrait, changing the orientation from landscape to portrait updates the UI but for some reason does not update the navigation mode property to NAVIGATION_MODE_LIST and hence mActionView.setDropdownSelectedPosition(position) is not called. See the following code of ActionBarImpl : 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 solution:
Through reflection we can get the tab spinner object and call 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 onPageSelected event.
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
Spinner spinner = getTabSpinner();
if (spinner != null) {
spinner.setSelection(position);
}
}
Referred this post https://gist.github.com/2657485
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…