How to save fragment state in android?

跟風遠走 提交于 2019-11-29 08:00:32

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();
    }

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.

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