Android冒险之旅-32-Bundle

本文详细介绍了如何在Android中使用Bundle进行数据传递,包括基本数据类型如String和int,以及如何通过实现Serializable接口传递自定义对象。通过示例代码展示了发送和接收数据的完整过程。
摘要由CSDN通过智能技术生成

介绍

Bundle,是Android开发中的一个类,用于Activity之间传输数据用。

传递基本数据类型

1. 发送数据

                //使用Bundle封装基本数据类型
                Bundle bundle = new Bundle();
                bundle.putString("name","alin");
                bundle.putInt("age",22);
                //创建Intent并将Bundle装入
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra("bundle",bundle);
                //发送
                startActivity(intent);

2. 接收数据

                //获取Bundle
                Bundle bundle = getIntent().getBundleExtra("bundle") ;
                //获取name
                String name = bundle.getString("name") ;
                //获取age
                int age = bundle.getInt("age") ;

 

传递对象

1. 对象实现序列化接口

public class Person implements Serializable {
    private String name;
    private int age;
    private static final long serialVersionUID = 1L;
    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;
    }
}

2. 发送数据

                //设置对象值
                Person person = new Person();
                person.setName("alin");
                person.setAge(22);
                //将person装入Bundle
                Bundle bundle = new Bundle();
                bundle.putSerializable("person",person);
                //创建Intent并将Bundle装入
                Intent intent = new Intent(this, MainActivity.class);
                intent.putExtra("bundle",bundle);
                //发送
                startActivity(intent);

3. 接收数据

                //获取Bundle
                Bundle bundle = getIntent().getBundleExtra("bundle") ;
                //获取Person对象
                Person person = (Person) bundle.getSerializable("person");
                //获取name属性
                String name = person.getName();
                //获取age属性
                int age = person.getAge() ;

END

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值