4

我在片段类中使用了多个选项卡。我未能保存片段的状态。我使用了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);
 }
4

1 回答 1

6

1) 显然,当使用 setRetainInstance(true) 时,onRestoreInstanceState 的 Bundle 为空。

https://stackoverflow.com/a/8488107/1011746

2) 没有必要,但更习惯于在对 outState 进行任何修改之前调用 super.onSaveInstanceState(outState)。与 onRestoreInstanceState(Bundle outState) 中的 super.onRestoreInstanceState(outState) 相同。

于 2012-10-28T20:00:48.977 回答