public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的Android课程中,教师使用了这段代码,但他们并没有对此进行详细解释.我该如何解释这段代码?我试过阅读文档,但我没有解释.
Vis*_*ave 20
这个概念叫做Parcelable
Parcelable是Java Serializable的Android实现.它假设某种结构和处理方式.这样,与标准Java序列化相比,可以相对快速地处理Parcelable.
要允许将自定义对象解析为另一个组件,需要实现android.os.Parcelable接口.它还必须提供一个名为CREATOR的静态final方法,该方法必须实现Parcelable.Creator接口.
您编写的代码将是您的模型类.
您可以在Activity中使用Parcelable,例如:
intent.putExtra("student", new Student("1")); //size which you are storing
Run Code Online (Sandbox Code Playgroud)
并获得此对象:
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");
Run Code Online (Sandbox Code Playgroud)
这里Student是一个模型类名.用你的替换它.
简单来说,Parcelable用于将模型类的整个对象发送到另一个页面.
在您的代码中,这是在模型中,它将int值大小存储到Parcelable对象以在其他活动中发送和检索.
参考:
--> Android 中可打包
Bundle 对象用于将数据传递给 Android 组件,它是专用对象的键/值存储。它类似于 Map 但只能包含这些专门的对象
您可以将以下对象类型放入 Bundle 中:
细绳
原语
可串行化
可分包
如果您需要通过 Bundle 传递客户对象,您应该实现 Parcelable 接口。
-->实现可打包
您可以为此创建一个 POJO 类,但您需要添加一些额外的代码以使其可 Parcelable。看看实施情况。
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);
this.id = data[0];
this.name = data[1];
this.grade = data[2];
}
@override
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];
}
};
}
Run Code Online (Sandbox Code Playgroud)
一旦创建了此类,您就可以轻松地通过 Intent 传递此类对象,并在目标 Activity 中恢复该对象。
intent.putExtra("student", new Student("1","Mike","6"));
Run Code Online (Sandbox Code Playgroud)
在这里,student 是您从捆绑包中解包数据所需的密钥。
Bundle data = getIntent().getExtras();
Student student = data.getParcelable("student");
Run Code Online (Sandbox Code Playgroud)
此示例仅显示 String 类型。但是,您可以打包任何您想要的数据。试试看。
| 归档时间: |
|
| 查看次数: |
7102 次 |
| 最近记录: |