Skip to content

Instantly share code, notes, and snippets.

@nolanlawson
Created July 11, 2013 13:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save nolanlawson/5975552 to your computer and use it in GitHub Desktop.
Save nolanlawson/5975552 to your computer and use it in GitHub Desktop.
Fix for Android's ActionBar, where navigational tabs don't work if the tabs are reduced to a dropdown (Spinner). This version is designed to work with Action Bar Sherlock. Based on the original discussion here: http://stackoverflow.com/questions/15409330/action-bar-selecttab-and-setselectednavigationitem-not-working
public void onPageSelected(int position) {
// When swiping between different app sections, select the corresponding tab.
// We can also use ActionBar.Tab#select() to do this if we have a reference to the
// Tab.
actionBar.setSelectedNavigationItem(position);
/*
*
* When paging between tabs, normally the dropdown list (spinnerAdapter) won't change properly. This
* occurs on small devices in landscape mode, i.e. when the tab labels are reduced to a dropdown to save space.
*
* Thanks to this StackOverflow discussion for figuring out how to solve this problem:
* http://stackoverflow.com/questions/15409330/action-bar-selecttab-and-setselectednavigationitem-not-working
*/
try {
//now use reflection to select the correct Spinner if
// the bar's tabs have been reduced to a Spinner
Activity activity = getActivity();
int actionBarResId = getResources().getIdentifier("action_bar", "id", "android");
if (actionBarResId == 0) { // not found, use action bar sherlock
actionBarResId = com.actionbarsherlock.R.id.abs__action_bar;
}
View action_bar_view = activity.findViewById(actionBarResId);
Class<?> action_bar_class = action_bar_view.getClass();
Field tab_scroll_view_prop = action_bar_class.getDeclaredField("mTabScrollView");
tab_scroll_view_prop.setAccessible(true);
//get the value of mTabScrollView in our action bar
Object tab_scroll_view = tab_scroll_view_prop.get(action_bar_view);
if (tab_scroll_view == null) return;
Field spinner_prop = tab_scroll_view.getClass().getDeclaredField("mTabSpinner");
spinner_prop.setAccessible(true);
//get the value of mTabSpinner in our scroll view
Object tab_spinner = spinner_prop.get(tab_scroll_view);
if (tab_spinner == null) return;
Method set_selection_method = tab_spinner.getClass().getSuperclass().getDeclaredMethod("setSelection", Integer.TYPE, Boolean.TYPE);
set_selection_method.invoke(tab_spinner, position, true);
} catch (NoSuchFieldException ignore) {
} catch (InvocationTargetException ignore) {
} catch (IllegalAccessException ignore) {
} catch (NoSuchMethodException ignore) {
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment