【发布时间】:2013-03-14 12:28:56
【问题描述】:
我有一个带有多个选项卡的 ActionBar,每个选项卡都链接到一个片段。我遇到的问题是,当我使用bar.selectTab(Tab) 或bar.setSelectedNavigationItem(int) 时,它不起作用。具体而言,当标签减少到动作栏中的旋转器时,会出现此问题。
【问题讨论】:
标签: android tabs android-actionbar spinner android-tabs
我有一个带有多个选项卡的 ActionBar,每个选项卡都链接到一个片段。我遇到的问题是,当我使用bar.selectTab(Tab) 或bar.setSelectedNavigationItem(int) 时,它不起作用。具体而言,当标签减少到动作栏中的旋转器时,会出现此问题。
【问题讨论】:
标签: android tabs android-actionbar spinner android-tabs
ActionBar 存在一个已知错误,特别是上面提到的方法,特别是当 ActionBar 的选项卡被缩减为 Spinner 时。
这是我的解决方法。如果选项卡已缩减为 Spinner,它会使用反射钻入 ActionBar。在您的 Activity 类中,创建如下方法:
/**
* A documented and yet to be fixed bug exists in Android whereby
* if you attempt to set the selected tab of an action bar when the
* bar's tabs have been collapsed into a Spinner due to screen
* real-estate, the spinner item representing the tab may not get
* selected. This bug fix uses reflection to drill into the ActionBar
* and manually select the correct Spinner item
*/
private void select_tab(ActionBar b, int pos) {
try {
//do the normal tab selection in case all tabs are visible
b.setSelectedNavigationItem(pos);
//now use reflection to select the correct Spinner if
// the bar's tabs have been reduced to a Spinner
View action_bar_view = findViewById(getResources().getIdentifier("action_bar", "id", "android"));
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, pos, true);
} catch (Exception e) {
e.printStackTrace();
}
}
这个例子的用法可能是:
private void delete_fragment_and_tab(String fragment_tag) {
//remove the fragment
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.remove(getFragmentManager().findFragmentByTag(fragment_tag));
//now remove the tab from the ActionBar
//and select the previous tab
ActionBar b = getActionBar();
Tab tab = b.getSelectedTab();
bar.removeTab(tab);
select_tab(bar, bar.getNavigationItemCount() -1);
}
【讨论】:
mTabScrollView 应该是组件内ScrollView 的Android 内部标识符。这似乎意味着标签没有“减少”到Spinner