Save the state of navigation drawer fragments

瘦欲@ 提交于 2019-12-10 08:57:48

问题


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.

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.

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.


回答1:


To not loose the state of your fragments when switching from one to another you should do "new Fragment()" only once, and keep the instance in a global variable.

But this will not fix the rotation problem. For the rotation problem, you should read this => http://blog.sqisland.com/2014/06/navigationdrawer-creates-fragment-twice.html Not easy but I haven't found another way yet.




回答2:


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

This will solve your problem.

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



来源:https://stackoverflow.com/questions/23050242/save-the-state-of-navigation-drawer-fragments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!