在Android屏幕上保存/恢复自定义ArrayList会旋转吗?

时间:2016-02-29 18:14:14

标签: android arraylist parcelable screen-rotation parcel

我有一个自定义的MovieItems ArrayList,我希望在屏幕旋转时保存和恢复。我查看了这篇文章 - How to save custom ArrayList on Android screen rotate? - 并实施并修改了一些代码,但保存和恢复似乎对我不起作用。

1)保存ArrayList:

public List<MovieItem> mItems = new ArrayList<>();

@Override
public void onSaveInstanceState(Bundle outState) {

    outState.putParcelableArrayList(MOVIE_KEY, (ArrayList<? extends Parcelable>) mItems);
    super.onSaveInstanceState(outState);
}

2)恢复ArrayList:

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (savedInstanceState != null)
        {

            mItems = savedInstanceState.getParcelableArrayList(MOVIE_KEY);
        }
        setRetainInstance(true);
......

    }

3)使MovieItem类Parcelable:

public class MovieItem implements Parcelable{



    private static final long serialVersionUID = 1L;

    private String mCaption;
    private String mId;
    private String mUrl;
    private String plot;
    private Double rating;
    private String release_date;
    private boolean favourite;

    public MovieItem() {
    }

    protected MovieItem(Parcel in) {
        mCaption = in.readString();
        mId = in.readString();
        mUrl = in.readString();
        plot = in.readString();
        release_date = in.readString();
        favourite = in.readByte() != 0;
        mTitle = in.readString();
    }

    public static final Creator<MovieItem> CREATOR = new Creator<MovieItem>() {
        @Override
        public MovieItem createFromParcel(Parcel in) {
            return new MovieItem(in);
        }

        @Override
        public MovieItem[] newArray(int size) {
            return new MovieItem[size];
        }
    };

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {

        out.writeString(mCaption);
        out.writeString(mId);
        out.writeString(mUrl);
        out.writeString(plot);
        out.writeDouble(rating);
        out.writeString(release_date);

    }

4 个答案:

答案 0 :(得分:4)

因为您有setRetainInstance(true),所以Fragment不会在屏幕旋转时销毁/重新创建。屏幕轮换后,Fragment会调用onSaveInstanceState(),但onCreate()部分不会发生。

答案 1 :(得分:0)

在相关活动标签的Manifest中添加此行,活动将自行处理轮换

android:configChanges="screenSize|orientation|screenLayout" 

测试它可能会帮助你

答案 2 :(得分:-1)

使用单一对象存储列表。     public enum MySingleton {     实例;     private MySingleton(){         的System.out.println( “在这里”);     }     private List mItems = new ArrayList&lt;&gt;();     public List getItems(){         返回mItems;     }     }

以及从任何地方访问您的数组MySingleton.INSTANCE.getItems()

答案 3 :(得分:-2)

您也可以尝试实现onRestoreInstanceState()方法。它在onStart()方法之后调用。您可以阅读onRestoreInstanceState