6

ArrayList 是在类级别定义的。这些是我的 savedInstance 方法:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putStringArrayList("savedList", list);
}


@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    list=savedInstanceState.getStringArrayList("savedList");
}

但是,当我改变方向时,ArrayList 是空白的

4

3 回答 3

3
TextView textviewname;
String textname;

 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);   
          setContentView(R.layout.activity_main);

       //declare the ui like this
    textviewname = (TextView) findViewById(R.id.textviewid);
       if(savedInstanceState==null){
       //the first time the activity was created
       //do the normal flow of the code
       //Example:getting the intent data for(savedList)or processing it
       Intent i = getIntent();
       textname = i.getStringExtra("savetext");
      //or textname="name_data";
       }else{
       //this is called when orientation change occur
       //get the savedata
        list=savedInstanceState.getStringArrayList("savedList");
        textname=savedInstanceState.getString("savetext");
       }

       textviewname.setText(textname);

}   
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    //saving data when orientation change trigger
    //saving  data before ondestroy happens
//onSaveInstanceState is called before going to another activity or orientation change
    outState.putStringArrayList("savedList", list);
    outState.putString("savetext", textname);
    //all imnportant data saved and can be restored
}


@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    //this is  only called after ondestroy-> oncreate occur
    list=savedInstanceState.getStringArrayList("savedList");
    textname=savedInstanceState.getString("savetext");
    //oncreate->onSaveInstanceState->ondestroy->oncreate->onRestoreInstanceState
}
于 2014-05-07T09:47:26.240 回答
3

当您用于onRestoreInstanceState()恢复状态时,它onStart()会在您定义适配器后使用保存的状态更新您的列表。您最好的选择是以onCreate()您在onRestoreInstanceState(). 您还可以重新定义适配器或调用notifyDataSetChanged().

于 2013-04-28T16:11:18.030 回答
0

尝试使用

list.addAll(savedInstanceState.getStringArrayList("savedList"));

反而

list=savedInstanceState.getStringArrayList("savedList");
于 2017-03-31T20:58:52.113 回答