简体   繁体   English

使用导航抽屉保存片段状态

[英]Save fragment state with navigation drawer

I want to save the state of a fragment while switching fragments using androids navigation drawer. 我想在使用androids导航抽屉切换片段时保存片段的状态。 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() . 要保持片段的状态,您必须在片段的onCreate()内调用setRetainInstance(true) 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) . 在这种情况下,您不必在抽屉的单击侦听器中创建新片段,而是必须使用findFragmentById(int id)findFragmentByTag(String tag)查找片段。 If the value returned is null then you can safely create a new one. 如果返回的值为null,则可以安全地创建一个新值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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