androidandroid-fragmentsfragmentresidemenu

How to save fragment state in android?


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.


Solution

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