好吧,有时片段会让人有些困惑,但过一段时间你就会习惯它们,并知道它们毕竟是你的朋友。
如果在片段的 onCreate() 方法上,您可以: setRetainInstance(true); 您的视图的可见状态将被保留,否则不会。
假设 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");
}
}
}