我在使用实现Parcelable的类读取字符串的ArrayList时遇到了麻烦。
我想将3个字符串列表发送到片段。我不明白的另一件事是我如何使用这个课程将这些数据实际发送到Fragment(我在其他地方读到你可以使用你自己的parcelable类来做这个,但我不知道'我确切地知道如何)。
以下是相关代码,我会在我认为需要帮助的地方发表评论。
package com.tsjd.HotMeals;
import java.util.ArrayList;
import android.os.Parcel;
import android.os.Parcelable;
public class RecipeListViewParcer implements Parcelable{
private ArrayList<String> titles;
private ArrayList<String> descriptions;
private ArrayList<String> images;
private RecipeListViewParcer(Parcel in) {
titles = in.readArrayList(String.class.getClassLoader()); //Need help here
descriptions = in.readArrayList(String.class.getClassLoader()); //Need help here
images = in.readArrayList(String.class.getClassLoader()); //Need help here
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeList(titles); //Need help here
out.writeList(descriptions); //Need help here
out.writeList(images); //Need help here
}
public static final Parcelable.Creator<RecipeListViewParcer> CREATOR
= new Parcelable.Creator<RecipeListViewParcer>() {
public RecipeListViewParcer createFromParcel(Parcel in) {
return new RecipeListViewParcer(in);
}
public RecipeListViewParcer[] newArray(int size) {
return new RecipeListViewParcer[size];
}
};
}
答案 0 :(得分:0)
我已经改变了你的类,添加了一个构造函数来初始化字段并重命名 RecipeListViewParcer到RecipeListViewParcel:)
package com.tsjd.HotMeals;
import java.util.ArrayList;
import android.os.Parcel;
import android.os.Parcelable;
public class RecipeListViewParcel implements Parcelable{
private ArrayList<String> titles;
private ArrayList<String> descriptions;
private ArrayList<String> images;
public RecipeListViewParcel(ArrayList<String> titles, ArrayList<String> descriptions, ArrayList<String> images) {
this.titles = titles;
this.descriptions = descriptions;
this.images = images;
}
// Convenient constructor to read from Parcel
private RecipeListViewParcel(Parcel in) {
titles = in.readArrayList(String.class.getClassLoader()); //Need help here
descriptions = in.readArrayList(String.class.getClassLoader()); //Need help here
images = in.readArrayList(String.class.getClassLoader()); //Need help here
}
public int describeContents() {
return 0;
}
// This method does actual job to write into the Parcel and called internally
// You need to override this method for each child class
@Override
public void writeToParcel(Parcel out, int flags) {
out.writeList(titles); //Need help here
out.writeList(descriptions); //Need help here
out.writeList(images); //Need help here
}
public static final Parcelable.Creator<RecipeListViewParcel> CREATOR
= new Parcelable.Creator<RecipeListViewParcel>() {
public RecipeListViewParcel createFromParcel(Parcel in) {
return new RecipeListViewParcel(in);
}
public RecipeListViewParcel[] newArray(int size) {
return new RecipeListViewParcel[size];
}
};
}