【问题标题】:Android Navigation Drawer wrong toolbar title onResumeAndroid Navigation Drawer 错误的工具栏标题 onResume
【发布时间】:2017-08-31 21:15:21
【问题描述】:

我的应用程序的主要活动中有一个导航抽屉。在活动的 onCreate 方法上,我像这样初始化其中一个片段:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState == null) {
        MenuItem menuItem = navigationView.getMenu().findItem(R.id.menu_history);
        openFragment(menuItem);
    }

public void openFragment(MenuItem menuItem){
    Fragment newFragment = null;

    switch (menuItem.getItemId()){
        case R.id.menu_history :
            newFragment = new HistoryFragment();
            break;
        //.....
    }

    if (newFragment != null){
        //Replace content frame in activity_main.xml with newFragment
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.content_frame, newFragment)
                .commit();

        menuItem.setChecked(true);
        getSupportActionBar().setTitle(menuItem.getTitle());
    }

    drawerLayout.closeDrawers();
}

这一切都很好,片段在启动时出现,工具栏上的标题是“历史”。但是当应用程序进入 onPause 然后 onResume 工具栏标题从“历史”切换到应用程序名称。我怀疑这是 onResume 没有正确打开片段/返回到以前的状态的问题,因为当我在 onResume 添加以下行时,问题停止了:

@Override
protected void onResume() {
    super.onResume();
    MenuItem menuItem = navigationView.getMenu().findItem(R.id.menu_history);
    openFragment(menuItem);
}

该解决方案似乎可以修复它,但这意味着它必须在每次应用程序恢复时重新加载带有动画的片段,这不是最佳的。有关如何解决此问题的任何想法?

如果有帮助,请重新创建我发现对使应用分屏有用的问题,因为它总是调用 onResume。谢谢。

【问题讨论】:

    标签: android android-fragments navigation-drawer android-lifecycle


    【解决方案1】:

    在你的 openFragment() 方法中,你写:

        getSupportActionBar().setTitle(menuItem.getTitle());
    

    这是唯一改变工具栏标题的东西。

    请注意,此代码本身与您的Fragments 无关。当您的活动被销毁并重新创建时,活动的Fragment 将被FragmentManager 成功(自动)销毁和重新创建...但是您的openFragment() 方法将不会再次运行,因此不会更新您的工具栏标题。

    有很多方法可以解决这个问题。可能正确的做法是在 Fragment 的生命周期方法之一中更新工具栏的标题。

    编辑:更新工具栏标题的合理位置是片段的onActivityCreated() 方法。这将在首次添加片段时和在重新创建期间运行。比如:

    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("hello world");
    }
    

    【讨论】:

      【解决方案2】:

      如果您不想每次都重新创建片段,您应该使用这里提到的 saveInstanceState:https://stackoverflow.com/a/17135346/1505074

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-08-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多