保存导航抽屉片段的状态 [英] Save the state of navigation drawer fragments

查看:53
本文介绍了保存导航抽屉片段的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在导航抽屉中的不同片段之间切换时,我试图将状态保存在导航抽屉片段中.例如:我从片段A开始触发一些事件,然后切换到片段B.然后,当我从片段B切换回片段A时,我想看到片段A的相同状态.

I am trying to save the state on the navigation drawer fragments as I toggle between different fragments within the navigation drawer. For Example: I start at Fragment A fire some events, then toggle to Fragment B. Then I want to see the same state of Fragment A when I toggle back to Fragment A from Fragment B.

我尝试使用onSavedInstanceState(Bundle savedInstanceState),但是只有在片段生命周期中方向发生变化时才会调用它.每当我切换到新片段时,都会创建一个新片段,但我不知道如何保存片段中的数据并在下次访问时重新加载.

I tried using the onSavedInstanceState(Bundle savedInstanceState) but it only gets called when the orientation changes in the fragment life cycle. A new fragment gets created whenever I toggle to a new fragment and I can't figure out how to save data from a fragment and reload it on another visit.

我也不想使用backstack(),因为它删除了所有片段,直到我要还原的片段为止.

I don't want to use backstack() either because it removes all the fragments up to the fragment that I want to restore.

下面是我如何称呼抽屉拨片上的片段.

Below is how I call the fragments on the drawer toggle.

private void selectItem(int position) {

    Fragment fragment;
    String TAG;

    switch (position) {
    case 0:
        fragment = new FragmntA();
        TAG = "A";
        break;
    case 1:
        fragment = new FragmentB();
        TAG = "B";
        break;
    case 2:
        fragment = new FragmentC();
        TAG = "C";
        break;
    case 3:
        fragment = new FragmentD();
        TAG = "D";
        break;
    case 4:
        fragment = new FragmentE();
        TAG = "E";
        break;
    default:
        fragment = new FragmentA();
        TAG = "A";
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();
    ft.replace(R.id.content_frame, fragment, TAG);
    ft.commit()

我不知道片段生命周期中是否有任何点可以保存其状态.任何帮助,将不胜感激.谢谢.

I don't know if there is any point in the fragment life cycle where I can save its state. Any help would be appreciated. Thanks.

推荐答案

在类和newInstance方法中将片段对象定义为静态,只有初始化为fragment为空,否则返回片段.

define fragment object as static in the class and in newInstance method only initialise is fragment is null otherwise just return the fragment.

这将解决您的问题.

但要更改方向,您将不得不使用saveinstancestate方法.

but for orientation change you will have to use on saveinstancestate method.

这篇关于保存导航抽屉片段的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆