获取Bundle 里的key,根据key来获取值

有些项目中会在两个activity中传输数据,然后根据传输的数据来显示或做其他处理。
比如在第一个activity 有多个按键,每个按键代表的不同的类型,这些按键启动的是同一个activity界面(复用同一个activity),在打开新的activity的时候需要显示不同的标题。
因为每个按键下发送了不同的类型,所以在新的activity中需要对发送过来的数据进行筛选并获取对应的值来显示。

//发送端
//新建方法,把相同的代码封装起来,避免出现重复的代码
private Intent setInformain(Context context, Class<?> cls, String key, String data) {
        Intent intent = new Intent(context, cls);
        Bundle bundle = new Bundle(); //创建bundle 实例,绑定需要传输的数据
        bundle.putString(key, data); //传送两个数据
        intent.putExtras(bundle); //把bundle绑定到intent上
        return intent;
    }
Button1: 
startActivity(setInformain(MainActivity.this, PreviewActivity.class, "name", "tom"));

button2:
startActivity(setInformain(MainActivity.this, PreviewActivity.class, "age", "18"));


//接收端
if (null != this.getIntent() && null != this.getIntent().getExtras()) {
    //接收到传送过来的Bundle 数据
    Bundle getBundle = this.getIntent().getExtras();
    //获取bundle中所有key的值
    Set<String> getKey = getBundle.keySet(); 
    for (String key : getKey) {
         if ("name".equals(key)) {
             String name = bundle.getString("name");   //获取值为 tom
         } else if ("age".equals(key)) {
            String age = bundle.getInt("age");   //获取值为 18
         }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值