操作栏.selectTab()和.setSelectedNavigationItem()不起作用

时间:2013-03-14 12:28:57

标签: android tabs android-actionbar spinner android-tabs

我有一个带有多个标签的ActionBar,每个标签链接到一个片段。我遇到的问题是,当我使用bar.selectTab(Tab)bar.setSelectedNavigationItem(int)时,它不起作用。特别是,当选项卡缩小到ActionBar中的Spinner时会出现此问题。

1 个答案:

答案 0 :(得分:4)

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); 
}