我在fragment类中使用了多个选项卡。我未能保存碎片的状态。我使用onSaveInstanceState()方法并在其中保存一个参数。但是当我回到这个片段时,保存的状态总是显示“null”。我试过所有关于这个的问题和答案,但我仍然面临着同样的问题。有人能帮我解决这个问题吗?
我的密码
@Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
super.onCreate(savedInstanceState);
Log.d("savedInstanceStateInfo1", "" + savedInstanceState);
if (null != savedInstanceState) {
nAndroids = savedInstanceState.getInt("nAndroids");
Log.d("NANDROIDS", "" + nAndroids);
}
}
// Log.d("State in oncreate : ",""+savedInstanceState);
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
Log.d("SavedinstanestateInfo", "" + savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
if (container == null) {
return null;
}
// final ActionBar ab=getActivity().getSupportActionBar();
View v = (LinearLayout) inflater.inflate(R.layout.infotab, container, false);
Log.d("SavedinstanestateInfo", "" + savedInstanceState);
return v;
}
@Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt("nAndroids", nAndroids);
super.onSaveInstanceState(outState);
}
最佳答案
1)显然,当使用setRetainInstance(true)时,onRestoreInstanceState的绑定为空。
https://stackoverflow.com/a/8488107/1011746
2)不需要,但在对outstate进行任何修改之前,更习惯于调用super.onSaveInstanceState(outstate)。与onrestoreInstanceState(bundle outstate)中的super.onrestoreInstanceState(outstate)相同。