Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 849
GibranG Avatar asked Oct 18 '13 11:10

GibranG


1 Answers

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.

like image 193
ZhDev Avatar answered Sep 20 '22 16:09

ZhDev