【问题标题】:Save BottomNavigationView selected item during screen rotation在屏幕旋转期间保存 BottomNavigationView 选定项
【发布时间】:2016-10-31 21:20:52
【问题描述】:

使用 ASL 的 25.0 BottomNavigationView 我遇到了一些麻烦,例如以编程方式保存选定项目(或他的索引)和选定项目。

【问题讨论】:

    标签: android android-support-library android-support-design


    【解决方案1】:

    不幸的是,在这个阶段,BottomNavigationView 中缺少 plenty 的功能。

    你的问题真的很有趣,我写了这个扩展的BottomNavigationView,它保留了状态,在你的情况下,保存了最后一个选定的项目。

    这里是gist to the code

    此扩展包括:

    • 提供两种公共方法来以编程方式设置和获取所选项目。
    • 仅保存和恢复最后一次选择的状态。

    让我们等到 ASL 开发者fix this

    【讨论】:

    • 为什么不将所需的项目设置为选中?就像他们在您发布的最后一个链接中建议的那样 (code.google.com/p/android/issues/…) bottomNavigationView.getMenu().findItem(selectedItem).setChecked(true);
    【解决方案2】:

    同意尼古拉的观点!

    我也创建了自己的gist

    要在轮换后保存状态,您需要添加Activity

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        outState.putInt("opened_fragment", bottomNavigation.getCurrentItem());
        super.onSaveInstanceState(outState);
    }
    

    并进入onCreate方法,就在设置BottomNavigationView之后:

    final defaultPosition = 0;
    final int bottomNavigationPosition = savedInstanceState == null ? defaultPosition :
                savedInstanceState.getInt("opened_fragment", defaultPosition);
    
    bottomNavigation.setCurrentItem(bottomNavigationPosition);
    

    这个要点的最大优点是:听众种类很少,它向您显示以前的选择位置,即使位置以编程方式设置,听众也会做出反应。一切都写在链接中,如果需要,请使用。

    【讨论】:

    • 如果一个位置被认为是视图感兴趣的,那么它必须保存在视图实现中。因此,通常的做法是将其保存在视图的适当保存和​​恢复状态方法中,而不是转到Activity 类。
    【解决方案3】:

    我正在使用 BottomNavigationView,这是应用程序在屏幕旋转时正常工作的代码。 首先,我创建了一个变量来保存所选菜单的 id
    private int saveState;

    通过在变量中获取所选菜单 id 来保存 id 的值

        @Override
        protected void onResume() {
            super.onResume();
            navigation.setSelectedItemId(saveState);
        }
    
        @Override
        public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
            super.onSaveInstanceState(outState, outPersistentState);
            saveState = navigation.getSelectedItemId();
        }
    

    然后在 onCreate 方法中检索 id 的值(如果可用)

            if(savedInstanceState!=null){
                navigation.setSelectedItemId(saveState);
            }else{
                FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                transaction.replace(R.id.content, MapFragment.newInstance());
                transaction.commit();
            }
    

    【讨论】:

      【解决方案4】:

      我遇到了同样的问题,我所做的是从 25.0.1 更新到 25.3.1 并且它开始正常工作而无需额外的代码.您可以查看Support Library Revision website 获取最新版本。

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-02-06
        相关资源
        最近更新 更多