How to save fragment state in android?

梦想的初衷 提交于 2019-12-29 07:13:10

问题


I have one HomeActivity from where I am calling the list of fragments. In HomeActivity I have sidemenu where all fragments are loaded.

Now,in this list i have one fragment called HomeFragment which display the Google Map with data, using webservice.

What i want is i want to load the Map dat only once(first time) fragment is loaded, not every time when click on sidemenu or come in from any other fragment.

My HomeFragment or any other fragments are loaded at once, not every time.


回答1:


You can hide/show fragment. No need to replace, remove. For ex, I have 2 fragments FragmentFeed and FragmentNotification, we can hide/show or add fragment.

Handle click menu:

if (tabId.equals(AppConstants.FEED)) {
                    pushFragments(tabId, getFragmentFeed());
                } else if (tabId.equals(AppConstants.NOTIFICATION)) {
                    pushFragments(tabId, getFragmentNotification());
                }

Handle show/hide and add fragment:

public void pushFragments(String tag, Fragment fragment) {

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();


        if (manager.findFragmentByTag(tag) == null) {
            ft.add(R.id.realtabcontent, fragment, tag);
        }

        Fragment fragmentFeed = manager.findFragmentByTag(TAG_FEED);
        Fragment fragmentNoti = manager.findFragmentByTag(TAG_NOTIFICATION);

        // Hide all Fragment
        if (fragmentFeed != null) {
            ft.hide(fragmentFeed);
        }
        if (fragmentNoti != null) {
            ft.hide(fragmentNoti);
        }

        // Show  current Fragment
        if (tag == TAG_FEED) {
            if (fragmentFeed != null) {
                ft.show(fragmentFeed);
            }
        }
        if (tag == TAG_NOTIFICATION) {
            if (fragmentNoti != null) {
                ft.show(fragmentNoti);
            }
        }



        ft.commitAllowingStateLoss();
    }



回答2:


You should use two things.

First onSavedInstance of your Fragment. Fill it with the info you want.

Second setRetainState(true). This will prevent your fragment from destroying even if it is detached. Hope this helps.



来源:https://stackoverflow.com/questions/42434392/how-to-save-fragment-state-in-android

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