简体   繁体   中英

Save fragment state with navigation drawer

I want to save the state of a fragment while switching fragments using androids navigation drawer. The fragment shouldn't refresh if it has been previously loaded. Is it possible?

To keep an fragment's state you have to call setRetainInstance(true) inside the fragment's onCreate() . What it does:

Control whether a fragment instance is retained across Activity re-creation (such as from a configuration change).

That keeps the state across the activity recreation, but in this case your activity won't be recreated, you are manually switching fragments using the drawer. In that case, instead of creating a new fragment inside the drawer's click listener, you'd have to look for the fragment using either findFragmentById(int id) or findFragmentByTag(String tag) . If the value returned is null then you can safely create a new one.

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