Android:处理配置更改内部片段

时间:2015-09-18 06:08:55

标签: android android-configchanges

我已将该列表保存在savedInstance方法中,但是当更改conf时,它的大小为零 以下是我的代码:

 @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setRetainInstance(true);
            setHasOptionsMenu(true);
            if(savedInstanceState == null) {
                arrayListPLPDetails = new ArrayList<>();
            }
            else
            {
                arrayListPLPDetails =  (ArrayList<HashMap<String,String>>)savedInstanceState.getSerializable(Tag.SAVED_INSTANCE)  ;
            }
        }

        @Override
        public void onSaveInstanceState(Bundle outState) {
            super.onSaveInstanceState(outState);
            outState.putSerializable(Tag.SAVED_INSTANCE,arrayListPLPDetails);
        }

2 个答案:

答案 0 :(得分:1)

覆盖片段内的方法“onConfigurationChanged”。

@Override
public void onConfigurationChanged(Configuration newConfig) {
  super.onConfigurationChanged(newConfig);

  // Checks the orientation of the screen
  if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
      Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
  } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
      Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
  }
}

检查以下链接

Android Docs for Fragment

答案 1 :(得分:-1)

当在onCreate()方法中调用setRetainInstance(true)方法时,会跳过onCreate()和onDestroy()方法,因此它不能在onCreate()中放置一些initail逻辑。