如何在Android屏幕上保存自定义ArrayList旋转?

时间:2012-09-19 22:34:31

标签: android object arraylist parcelable screen-rotation

我有ArrayList个自定义对象,我希望能够在屏幕上保存和恢复旋转。

我知道如果我要将onSaveInstanceState作为自己的类,实现onRestoreInstanceState或{{1},我可以使用ArrayListParcelable来完成此操作} ...但是有没有办法在不创建另一个类的情况下做到这一点?

4 个答案:

答案 0 :(得分:83)

您无需创建新类来传递自定义对象的ArrayList。您应该只为对象实现Parcelable类,并使用onSaveInstanceState()onRestoreInstanceState()中的Bundle#putParcelableArrayList()。此方法将自行存储Parcelables的ArrayList。


因为Parcelables(和Serializables and Bundles)的主题有时让我头疼,这里是一个包含存储在Bundle中的自定义Parcelable对象的ArrayList的基本示例。 (这是剪切和粘贴可运行,无需布局。)

实施Parcelable

public class MyObject implements Parcelable {
    String color;
    String number;

    public MyObject(String number, String color) {
        this.color = color;
        this.number = number;
    }

    private MyObject(Parcel in) {
        color = in.readString();
        number = in.readString();
    }

    public int describeContents() {
        return 0;
    }

    @Override
    public String toString() {
        return number + ": " + color;
    }

    public void writeToParcel(Parcel out, int flags) {
        out.writeString(color);
        out.writeString(number);
    }

    public static final Parcelable.Creator<MyObject> CREATOR = new Parcelable.Creator<MyObject>() {
        public MyObject createFromParcel(Parcel in) {
            return new MyObject(in);
        }

        public MyObject[] newArray(int size) {
            return new MyObject[size];
        }
    };
}

保存/恢复状态

public class Example extends ListActivity {
    ArrayList<MyObject> list;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        if(savedInstanceState == null || !savedInstanceState.containsKey("key")) {
            String[] colors = {"black", "red", "orange", "cyan", "green", "yellow", "blue", "purple", "magenta", "white"};
            String[] numbers = {"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};

            list = new ArrayList<MyObject>();
            for(int i = 0; i < numbers.length; i++) 
                list.add(new MyObject(numbers[i], colors[i]));
        }
        else {
            list = savedInstanceState.getParcelableArrayList("key");
        }

        setListAdapter(new ArrayAdapter<MyObject>(this, android.R.layout.simple_list_item_1, list));
    }

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

答案 1 :(得分:3)

您可以使用onRetainNonConfigurationInstance()。它允许您在配置更改之前保存任何对象,并在使用getLastNonConfigurationInstanceState()后恢复它。

活动内部:

    @Override
    public Object onRetainNonConfigurationInstance() {
        return myArrayList;
    }

内部onCreate()

    try{
        ArrayList myArrayList = (ArrayList)getLastNonConfigurationInstance();
    } catch(NullPointerException e) {}

处理运行时更改:http://developer.android.com/guide/topics/resources/runtime-changes.html 文档:http://developer.android.com/reference/android/app/Activity.html#onRetainNonConfigurationInstance%28%29

答案 2 :(得分:0)

public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    ArrayList<Integer> id=new ArrayList<>();
    ArrayList<String> title=new ArrayList<>();
    for(int i=0;i<arr.size();i++){
        id.add(arr.get(i).id);
        title.add(arr.get(i).title);
    }
    outState.putIntegerArrayList("id",id);
    outState.putStringArrayList("title",title);
}

答案 3 :(得分:-3)

是的,您可以将您的复合对象保存在共享首选项中。让我们说:

Student mStudentObject = new Student();
     SharedPreferences appSharedPrefs = PreferenceManager
      .getDefaultSharedPreferences(this.getApplicationContext());
      Editor prefsEditor = appSharedPrefs.edit();
      Gson gson = new Gson();
      String json = gson.toJson(mStudentObject);
      prefsEditor.putString("MyObject", json);
      prefsEditor.commit(); 

现在您可以将对象检索为:

     SharedPreferences appSharedPrefs = PreferenceManager
     .getDefaultSharedPreferences(this.getApplicationContext());
     Editor prefsEditor = appSharedPrefs.edit();
     Gson gson = new Gson();
     String json = appSharedPrefs.getString("MyObject", "");
     Student mStudentObject = gson.fromJson(json, Student.class);