我真的对Fragment的内部状态感到困惑。
我有一个 Activity 一次只保存一个片段,如果要显示另一个片段,则将其替换。在文档中,只有在调用Activity的onSaveInstanceState
时才调用onSaveInstanceState
(在我的情况下未调用)。
如果我停止我的Fragment,我会自己将其状态存储在Singleton中(是的,我知道我也讨厌Singletons,但这样做不是我的主意)。
因此,我必须重新创建整个ViewHirarchy
,创建新的Views(通过使用关键字new
),还原其状态并以onCreateView
返回它们。
我还在此 View 中有一个复选框,我明确不想从中存储其状态。
但是,FragmentManager
希望是“智能的”,并使用我从未创建过的 bundle 软件调用onViewStateRestored
,并“恢复”旧CheckBox
的状态并将其应用于我的NEW CheckBox。这引发了很多问题:
我可以通过onViewStateRestored
控制 bundle 包吗?
FragmentManager如何获取(可能是垃圾收集的)CheckBox的状态并将其应用于新的CheckBox?
为什么只保存复选框的状态(不保存TextViews的状态??)
总结一下:onViewStateRestored
如何工作?
注意我正在使用Fragmentv4,因此onViewStateRestored
不需要API> 17
最佳答案
好吧,有时候碎片会让人有些困惑,但是过了一会儿您就会习惯它们了,并且知道它们毕竟是您的 friend 。
如果在片段的onCreate()方法上,则执行以下操作:setRetainInstance(true);您的 View 的可见状态将保留,否则将不保留。
假设一个名为F的片段“f”,其生命周期将如下所示:
-实例化/附加/显示它时,这些是f的方法,按此顺序调用:
F.newInstance();
F();
F.onCreate();
F.onCreateView();
F.onViewStateRestored;
F.onResume();
此时,您的片段将在屏幕上可见。
假定设备已旋转,因此必须保留片段信息,这是由旋转触发的事件流:
F.onSaveInstanceState(); //save your info, before the fragment is destroyed, HERE YOU CAN CONTROL THE SAVED BUNDLE, CHECK EXAMPLE BELLOW.
F.onDestroyView(); //destroy any extra allocations your have made
//here starts f's restore process
F.onCreateView(); //f's view will be recreated
F.onViewStateRestored(); //load your info and restore the state of f's view
F.onResume(); //this method is called when your fragment is restoring its focus, sometimes you will need to insert some code here.
//store the information using the correct types, according to your variables.
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("foo", this.foo);
outState.putBoolean("bar", true);
}
@Override
public void onViewStateRestored(Bundle inState) {
super.onViewStateRestored(inState);
if(inState!=null) {
if (inState.getBoolean("bar", false)) {
this.foo = (ArrayList<HashMap<String, Double>>) inState.getSerializable("foo");
}
}
}
关于android - Fragments中的 `onViewStateRestored`如何工作?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17792132/