Android最简单数据传递之通过实现Parcelable接口
2019-04-10 15:54
465 查看
通过实现Parcelable接口
这个是通过实现Parcelable接口,把要传的数据打包在里面,然后在接收端自己分解出来。这个是Android独有的,在其本身的源码中也用得很多,效率要比Serializable相对要好。
Parcelable方式实现的原理是将一个完整的对象进行分解 , 而分解后的每一部分都是Intent所支持的数据类型 , 这样也就实现传递对象的功能了 .
Parcelable的实现方式 :
[code]public class Student implements Parcelable { private String name; private int age; public Student() { } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } protected Student(Parcel in) { name = in.readString(); age = in.readInt(); } public static final Creator<Student> CREATOR = new Creator<Student>() { @Override public Student createFromParcel(Parcel in) { return new Student(in); } @Override public Student[] newArray(int size) { return new Student[size]; } }; @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(name); dest.writeInt(age); } }
Parcelable的实现方式要稍微复杂一些 , 首先让Student类去实现了Parcelable接口 , 这样就必须重写describeContents()和writeToParcel()这两个方法 . 其中describeContents()方法可以直接返回0就可以了 , 而writeToParcel()方法中需要调用Parcel的writeXxx()方法 , 将Student类中的字段一一写出 . 注意 , 字符串数据就调用writeString()方法 , 整数数据就调用writeInt()方法 , 一次类推 .
除此之外 , 我们还必须在Student类中提供一个名为CREATOR的常量 , 这里创建了Parcelable.Creator接口的一个实现 , 并将泛型指定为Student . 接着需要重写createFromParcel()和newArray()这两个方法 . 在createFromParcel()方法中我们要去创建一个Student对象 , .而newArray()方法只需要new出一个Student数组 , 并传入size()作为数据的大小就可以了 .
1,设置参数
[code]Student student = new Student(); student.setAge(25); student.setName("lyx"); Intent intent4 = new Intent(MainActivity.this, ParcelableActivity.class); intent4.putExtra("parcelable", student); startActivity(intent4);
2,接收参数
[code] this.setTitle("Parcelable例子"); //接收参数 Intent i = getIntent(); Student student = i.getParcelableExtra("parcelable"); TextView tv = findViewById(R.id.tv); tv.setText("姓名:" + student.getName() + "--年龄:" + student.getAge());
相关文章推荐
- Android开发:使用序列化接口Parcelable、Serializable实现Activity间传递复杂数据类型参数
- Android最简单数据传递之通过单例模式实现参数传递
- Android开发:使用序列化接口Parcelable、Serializable实现Activity间传递复杂数据类型参数
- android中通过实现Parcelable来在两个页面之间传递对象的简单使用
- Android开发:使用序列化接口Parcelable、Serializable实现Activity间传递复杂数据类型参数
- Android中Parcelable接口跨进程传递复杂数据的应用
- Android通过POST方式传递数据到服务器简单demo
- Android实现通过浏览器点击链接打开本地应用(APP)并拿到浏览器传递的数据
- 如何通过实现parcelable接口传递值对象
- android实现通过浏览器点击链接打开本地应用(APP)并拿到浏览器传递的数据
- Android 通过(Parcelable)序列化ArrayList实现Activity间传递ArrayList
- Android实现通过浏览器点击链接打开本地应用(APP)并拿到浏览器传递的数据
- Android 通过(Parcelable)序列化对象实现Activity间传递对象
- android实现通过浏览器点击链接打开本地应用(APP)并拿到浏览器传递的数据
- Android如何通过parcelable实现跨进程之间多态的类型的传递。
- android实现通过浏览器点击链接打开本地应用(APP)并拿到浏览器传递的数据
- Android get/ post 方法 传递网络数据 -简单的翻译功能实现(GET)
- Android使用webview控件加载本地html,通过Js与后台Java实现数据的传递
- Android实现通过浏览器点击链接打开本地应用(APP)并拿到浏览器传递的数据
- 使用序列化接口Parcelable、Serializable实现Activity间传递复杂数据类型参数