【问题标题】:What is Parcelable in android什么是 android 中的 Parcelable
【发布时间】:2018-08-21 07:11:41
【问题描述】:
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();
  }
}

在我的 Android 课程中,讲师使用了这段代码,但他们并没有完全解释这一点。我该如何解释这段代码?我尝试阅读文档,但未能解释。

【问题讨论】:

  • 我还是不明白__that__这些方法是如何被调用的......

标签: java android


【解决方案1】:

这个概念叫做Parcelable

Parcelable 是 Java Serializable 的 Android 实现。它采用某种结构和处理方式。与标准 Java 序列化相比,这种方式可以相对快速地处理 Parcelable。

为了让您的自定义对象被解析到另一个组件,他们需要实现 android.os.Parcelable 接口。它还必须提供一个名为 CREATOR 的静态最终方法,该方法必须实现 Parcelable.Creator 接口。

您编写的代码将成为您的模型类。

您可以在 Activity 中使用 Parcelable,例如:

intent.putExtra("student", new Student("1")); //size which you are storing

并得到这个对象:

Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");

这里的 Student 是一个模型类名。用你的替换它。

简单来说,Parcelable 用于将模型类的整个对象发送到另一个页面。

在您的代码中,这是在模型中,它将 int 值 size 存储到 Parcelable 对象以在其他活动中发送和检索。

参考:

Tutorial 1

Tutorial 2

Tutorial 3

【讨论】:

  • 通俗地说:使用 Parcelable 将对象转换为可以读取的字节序列。活动之间转移。
  • 我还发现此链接上的解释非常有用,因为它还指出了实现 Parcelable 接口时的注意事项:Using Parcelable
猜你喜欢
  • 2012-06-20
  • 1970-01-01
  • 2016-07-25
  • 2023-03-21
  • 1970-01-01
  • 2016-08-01
  • 1970-01-01
  • 2013-11-25
  • 1970-01-01
相关资源
最近更新 更多