4

我有一个带有列表导航模式的 ActionBar。问题是从导航微调器中选择项目后,当屏幕方向更改时,导航微调器选择的索引重置为 0。

如何在配置更改期间保留微调器的选定索引?

谢谢

4

1 回答 1

5

您应该覆盖onSaveInstanceState并保存选定的导航列表位置以捆绑。不要忘记恢复位置onCreate

看下面的例子:

public class MainActivity
{

    private static final String CURRENT_FRAGMENT_TAG = "fragmentPosition";

    @Inject @Named("navigationFragments")
    private Provider<? extends Fragment>[] fragmentProviders;

    @Override
    protected void onCreate(Bundle bundle)
    {
        super.onCreate(bundle);

        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
        actionBar.setListNavigationCallbacks(ArrayAdapter.createFromResource(
            this, R.array.navigation_menu, android.R.layout.simple_list_item_1), new ActionBar.OnNavigationListener()
        {
            @Override
            public boolean onNavigationItemSelected(int itemPosition, long itemId)
            {
                final String fragmentTag = "fragment-" + itemPosition;

                // to prevent fragment re-selection and loosing early saved state
                if (getSupportFragmentManager().findFragmentByTag(fragmentTag) != null)
                {
                    return true;
                }

                final Fragment fragment = fragmentProviders[itemPosition].get();
                getSupportFragmentManager().beginTransaction().
                    replace(android.R.id.content, fragment, fragmentTag).
                    commit();
                return true;
            }
        });
        actionBar.setSelectedNavigationItem(bundle != null
            ? bundle.getInt(CURRENT_FRAGMENT_TAG)
            : 0);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState)
    {
        super.onSaveInstanceState(outState);
        outState.putInt(CURRENT_FRAGMENT_TAG, getSupportActionBar().getSelectedNavigationIndex());
    }

    /*

        Additional stuff here

     */

}

Provider<? extends Fragment>[] fragmentProviders是创建新片段的工厂方法对象的列表。如果您不使用actionbarsherlock ,请替换getSupportActionBar()togetActionBar()getSupportFragmentManager()togetFragmentManager()

于 2012-12-12T21:22:15.320 回答