Save fragment state with navigation drawer

自闭症网瘾萝莉.ら 提交于 2019-12-01 14:51:21

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19448946/save-fragment-state-with-navigation-drawer

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