本文介绍了在 Android 屏幕上保存/恢复自定义 ArrayList 旋转?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的 MovieItem ArrayList,我想在屏幕旋转时保存和恢复它.我查看了这篇文章 - 如何在 Android 屏幕上保存自定义 ArrayList旋转? - 并实施和调整了一些代码,但保存和恢复似乎对我不起作用.

I have a custom ArrayList of MovieItems that I want to save and restore on screen rotation. I checked out this post - How to save custom ArrayList on Android screen rotate? - and implemented and adapted some of the codes but the saving and restoring don't seem to be working for me.

1) 保存 ArrayList:

1) Saving the 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:

2) Restoring the ArrayList:

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        if (savedInstanceState != null)
        {

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

    }

3) 制作 MovieItem 类 Parcelable:

3) Making the MovieItem class 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);

    }

推荐答案

在你的 Manifest 中的相关活动标签中添加这一行,活动将自行处理旋转

add this line in your Manifest in relevant activity tag , and activity will handle rotation itself

android:configChanges="screenSize|orientation|screenLayout"

测试一下也许对你有帮助

test it maybe help you

这篇关于在 Android 屏幕上保存/恢复自定义 ArrayList 旋转?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 22:18