简体   繁体   English

恢复片段的状态

[英]Restoring state of fragment

I have a Fragment F attached on Activity A. When another activity becomes front-activity it is called onSaveInstanceState . 我在活动A上附加了一个Fragment F.当另一个活动变为前端活动时,它被称为onSaveInstanceState I've overrided that function and it looks like: 我已经覆盖了这个功能,它看起来像:

public void onSaveInstanceState(Bundle outState){
 saveState_to_outstate
}

Now, when the Fragment F is front again it is called onViewCreated(View view, Bundle savedInstanceState) . 现在,当片段F再次位于前面时,它被调用onViewCreated(View view, Bundle savedInstanceState) I would like to restore previously saved state but I cannot because savedInstanceState is null though it was written before in onSaveInstanceState . 我想恢复以前保存的状态,但我不能因为savedInstanceState为null,尽管它之前是在onSaveInstanceState中写的。

Why it happened? 为什么会这样?

If you want to restore Fragment F with previous Data. 如果要使用以前的数据恢复Fragment F. As according to my knowledge you should perform inside onViewStateRestored() method of Fragment. 根据我的知识,你应该在onViewStateRestored()方法中执行。

OnViewStateRestored (Bundle) tells the fragment that all of the saved state of its view hierarchy has been restored. OnViewStateRestored(Bundle)告诉片段已恢复其视图层次结构的所有已保存状态。 you Should visit this link for your reference: Fragment 您应该访问此链接供您参考: 片段

Method A: You can pass the data from Activity A to Fragment F by bundle or intent. 方法A:您可以通过bundle或intent将数据从Activity A传递到Fragment F. it's similar to usage of saving instance. 它类似于保存实例的用法。 Send data from activity to fragment in android 在android中将数据从活动发送到片段

MethodB: You can only use following function with onCreate() at the same place, either fragment F or Activity A. 方法B:你只能在同一个地方使用跟随函数onCreate() ,片段F或活动A.

public void onSaveInstanceState(Bundle outState){ outState.putInt("STATE_NAME", 123);//123 is the data you gonna save super.onSaveInstanceState(outState);//Don't forget to put this }

MethodC: Use hardcode-like SharePreference Android Shared preferences example ,it's also like the bundle and intent, and it won't be effected by Activity or fragment life periods. 方法C:使用类似硬编码的SharePreference Android共享首选项示例 ,它也像bundle和intent,它不会受Activity或片段生命周期的影响。

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

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