简体   繁体   中英

How to save specific fragment state in Android app

I'm developing an application with Drawer Navigation and I want to save state of single fragment. If I switch to this fragment from another it refreshes and I have to avoid it. Other fragments must be reloading. What can I do? This is my code:

    @Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    Fragment fragment = null;
    int id = item.getItemId();

    if (id == R.id.nav_places)
    {
        fragment = new Places();
    }
    else if (id == R.id.nav_map)
    {
        fragment = mapFragment; // fragment which I want to keep in memory
    }
    else if (id == R.id.nav_about)
    {
        fragment = new About();
    }

    FragmentManager fragmentManager = getSupportFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_container, fragment).commit(); //NULL POINTER
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

Regards!

As I understand it, your problem is that once you return to a previous fragment from a current fragment, the previous fragment's state is initial, and doesn't reflect how it was configured by the user the last time it was displayed, correct?

What you can do in this case is to use to use the ViewPager to display your fragments and refresh the fragment manually, reading the data from SharedPreferences or a static class, like so:

// This works like onRefresh(), when the user returns to the fragment.
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        ... RELOAD VARIABLES AND UPDATE YOUR FRAGMENT INTERFACE ...
    }
}

Of course prior to that you need to write all of the relevant data to SharedPreferences or a static class.

In general I find that if I set up my fragment's onCreateView() correctly, initializing my controls with SharedPreferences , then I don't even have to resort to the above trick. I haven't found a way to grab a fragment and save its state automatically. You need to do the leg work yourself. Good luck! :)

You create a variable and assign MapFragment instance to it. You only instantiate once and then reuse the variable like

private Fragment mapFragment = new MapFragment();

...
else if (id == R.id.nav_map)
{
    fragment = mapFragment; 
}

Would this works for you?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM