我不想在屏幕旋转后重新加载RecyclerView
。我发现我需要从Adapter
存储/恢复List
。不是吗?
但是有一个问题:
Found java.util.List<Department> requried java.util.ArrayList<?extends android.os.Parcelable>
当我尝试将list放入包中时:
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("key", mAdapter.getList());
}
mAdapter.getList()
从RecyclerView的适配器返回List<Department>
。
但我在Department
模型类中实现了Parcelable
:
@Parcel
public class Department implements UrlInterface,Parcelable {
@SerializedName("department_id")
@Expose
String departmentId;
@SerializedName("short_name")
@Expose
String shortName;
@Expose
String url;
@Expose
HashMap<Integer, Category> categories;
public Department() {}
protected Department(android.os.Parcel in) {
departmentId = in.readString();
shortName = in.readString();
url = in.readString();
}
public static final Creator<Department> CREATOR = new Creator<Department>() {
@Override
public Department createFromParcel(android.os.Parcel in) {
return new Department(in);
}
@Override
public Department[] newArray(int size) {
return new Department[size];
}
};
public String getDepartmentId() { return departmentId; }
public void setDepartmentId(String departmentId) { this.departmentId = departmentId; }
public String getShortName() { return shortName; }
public void setShortName(String shortName) { this.shortName = shortName; }
@Override
public String getUrl() { return url; }
@Override
public String getFullName() { return shortName; }
public void setUrl(String url) { this.url = url; }
public HashMap<Integer, Category> getCategories() { return categories; }
@Override
public String toString() { return shortName; }
@Override
public String getImageUrl() { return null; }
@Override
public int describeContents() { return 0; }
@Override
public void writeToParcel(android.os.Parcel dest, int flags) {
dest.writeString(departmentId);
dest.writeString(shortName);
dest.writeString(url);
}
}
出什么问题了?
发布于 2016-06-22 11:28:48
ArrayList
是List
的一个子类,从List
到ArrayList
....bad idea...and的转换会产生问题,特别是对于可包裹的东西。
所以快速的解决方案是这样做:
outState.putParcelableArrayList("key", new ArrayList<Department>(mAdapter.getList()));
。
发布于 2020-05-16 00:33:43
上面的解决方案对我不起作用,继续抛出错误。下面的解决方案,由Android Studio提供的hind为我所用-
outState.putParcelableArrayList("message_list", (ArrayList<? extends Parcelable>) messageList);
以防其他人也在这个帖子上寻找类似的解决方案!
https://stackoverflow.com/questions/37966608
复制