如何在安卓屏幕上保存自定义数组列表旋转



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

我知道这可以通过onSaveInstanceStateonRestoreInstanceState来完成,如果我要使ArrayList成为自己的类,它实现ParcelableSerializable......但是有没有办法在不创建另一个类的情况下做到这一点?

无需创建新类即可传递自定义对象的 ArrayList。您应该简单地为您的对象实现 Parcelable 类,并在 onSaveInstanceState()onRestoreInstanceState() 中使用 Bundle#putParcelableArrayList() 。此方法将单独存储包裹的数组列表。


因为包裹对象(以及可序列化对象和捆绑包)的主题有时会让我头疼,所以下面是一个包含存储在捆绑包中的自定义可包裹对象的 ArrayList 的基本示例。(这是可剪切和粘贴运行的,无需布局。

实现可包裹

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);
    }
}
您可以使用

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

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);
}

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

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);

相关内容

  • 没有找到相关文章

最新更新