• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

android - 如何使我的自定义对象 Parcelable?

[复制链接]
菜鸟教程小白 发表于 2022-8-1 01:20:17 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

我正在尝试使我的对象可打包。但是,我有自定义对象,这些对象有 ArrayList我制作的其他自定义对象的属性。

最好的方法是什么?



Best Answer-推荐答案


您可以找到一些示例 here , here (code is taken here) , 和 here .

您可以为此创建一个 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);
           // 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 中恢复这个对象。
intent.putExtra("student", new Student("1","Mike","6"));

在这里,学生是您从 bundle 中解包数据所需的 key 。
Bundle data = getIntent().getExtras();
Student student = (Student) data.getParcelable("student");

此示例仅显示 String类型。但是,您可以打包任何类型的数据。试试看。

编辑:另一个 example , 由 Rukmal Dias 建议.

关于android - 如何使我的自定义对象 Parcelable?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7181526/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap