什么是Android中的Parcelable [英] What is Parcelable in android

查看:156
本文介绍了什么是Android中的Parcelable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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课程中,教师使用了这块代码,他们没有解释这一点。我该如何解释这段代码?我尝试阅读文档,但我没有解释。

During my Android course, the instructor used this block of code and they didn't quite explained this. How can I interpret this code? I tried reading the documentation but I failed to interpret.

推荐答案

这个概念叫做 Parcelable

This concept is called Parcelable

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

A Parcelable is the Android implementation of the Java Serializable. It assumes a certain structure and way of processing it. This way a Parcelable can be processed relatively fast, compared to the standard Java serialization.

要允许将自定义对象解析为另一个组件,他们需要实现android。 os.Parcelable接口。它还必须提供一个名为CREATOR的静态final方法,它必须实现Parcelable.Creator接口。

To allow your custom object to be parsed to another component they need to implement the android.os.Parcelable interface. It must also provide a static final method called CREATOR which must implement the Parcelable.Creator interface.

您编写的代码将是您的模型类。

The code you have written will be your model class.

你可以在Activity中使用Parcelable,如:

You can use Parcelable in Activity like :

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

并获取此对象:

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

此处学生是模型类名。用你的替换它。

Here Student is a model class name. replace this with yours.

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

In simple terms Parcelable is used to send a whole object of a model class to another page.

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

In your code this is in the model and it is storing int value size to Parcelable object to send and retrieve in other activity.

参考:

教程1

教程2

教程3

这篇关于什么是Android中的Parcelable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆