How can I make my custom objects Parcelable?(如何使我的自定义对象 Parcelable?)
问题描述
我正在尝试使我的对象可包裹.但是,我有自定义对象,这些对象具有我制作的其他自定义对象的 ArrayList
属性.
I'm trying to make my objects Parcelable. However, I have custom objects and those objects have ArrayList
attributes of other custom objects I have made.
最好的方法是什么?
推荐答案
你可以找到一些例子 这里,这里(代码在这里)和这里.
You can find some examples of this here, here (code is taken here), and here.
您可以为此创建一个 POJO 类,但您需要添加一些额外的代码以使其 Parcelable
.看看实现.
You can create a POJO class for this, but you need to add some extra code to make it Parcelable
. Have a look at the implementation.
public class Student implements Parcelable{
private String id;
private String name;
private String grade;
// Constructor
public Student(String id, String name, String grade){
this.id = id;
this.name = name;
this.grade = grade;
}
// Getter and setter methods
.........
.........
// Parcelling part
public Student(Parcel in){
String[] data = new String[3];
in.readStringArray(data);
// the order needs to be the same as in writeToParcel() method
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
@Оverride
public int describeContents(){
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {this.id,
this.name,
this.grade});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Student createFromParcel(Parcel in) {
return new Student(in);
}
public Student[] newArray(int size) {
return new Student[size];
}
};
}
一旦你创建了这个类,你就可以像这样通过Intent
轻松地传递这个类的对象,并在目标Activity中恢复这个对象.
Once you have created this class, you can easily pass objects of this class through the Intent
like this, and recover this object in the target activity.
intent.putExtra("student", new Student("1","Mike","6"));
在这里,学生是您从捆绑包中解包数据所需的密钥.
Here, the student is the key which you would require to unparcel the data from the bundle.
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
此示例仅显示 String
类型.但是,您可以打包任何类型的数据.试试看.
This example shows only String
types. But, you can parcel any kind of data you want. Try it out.
另一个 示例,由 Rukmal Dias.
这篇关于如何使我的自定义对象 Parcelable?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何使我的自定义对象 Parcelable?


- 如何检查发送到 Android 应用程序的 Firebase 消息的传递状态? 2022-01-01
- 在测试浓缩咖啡时,Android设备不会在屏幕上启动活动 2022-01-01
- Android viewpager检测滑动超出范围 2022-01-01
- Android - 拆分 Drawable 2022-01-01
- 用 Swift 实现 UITextFieldDelegate 2022-01-01
- android 4中的android RadioButton问题 2022-01-01
- MalformedJsonException:在第1行第1列路径中使用JsonReader.setLenient(True)接受格式错误的JSON 2022-01-01
- Android - 我如何找出用户有多少未读电子邮件? 2022-01-01
- 使用自定义动画时在 iOS9 上忽略 edgesForExtendedLayout 2022-01-01
- 想使用ViewPager,无法识别android.support.*? 2022-01-01