0

我有一个带有多个选项卡的 ActionBar,每个选项卡都链接到一个片段。我遇到的问题是,当我使用bar.selectTab(Tab)or时bar.setSelectedNavigationItem(int),它不起作用。Specifically, this problem occurs when the tabs get reduced down to a Spinner in the ActionBar.

4

1 回答 1

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); 
}
于 2013-03-14T12:28:56.753 回答