Android Bundle容器

1
2
3
title: Android Bundle容器
date: 2020-07-06 09:07:20
tags: android

Android Bundle容器

凡走过,必留下痕迹。

介绍:类似于Map的Key-value的形式,实现了Parcelable

作用:Bundle 与Intent 一样,都可以在Activity、Fragment中传递数据。

场景:

Activity的onSaveInstanceState(Bundle outState)

Activity的onCreate(Bundle saveInstanceState)

Fragment的argment属性

Message的setData、获取:meg.getData.getString(“key”)

Intent.putExtras(Bundle bundle)

清楚数据:clear()

例子:

第一种写法,用于批量添加数据到Intent:

1
2
3
4
Intent intent = new Intent();
  Bundle bundle = new Bundle();//该类用作数据载体
  bundle.putString("name","Mike");
  intent.putExtras(bundle);//可追加额外的数据,key同名的数据会被替换,与Map用法类似

第二种写法:不通过Bundle,把数据一个个地添加进Intent,这种写法使用起来比较方便,代码更简洁。

1
2
Intent intent = new Intent();
  intent.putExtra("name","XXX");//注意:不是putExtras,

取值:

传完数据后,现在看看如何将Intent和Bundle取出来:
  ①直接使用this.getIntent() 得到传来的Intent
  ②然后在这个Intent的基础上调用getExtras()得到Bundle
  ③根据数据类型可以从Bundle中get数据。
  比如

String str=bundle.getString(“Name”);得到键为“Name”的字符串

int num=bundle.getInt(“code”);得到键为“code”的整型。
  另外一定要注意getExtrasgetExtra的区别。带s用于Bundle添加值和取值。

Message.setData同理Intent的Bundle使用

用Bundle向Fragment传递参数不会在Activit被重建时销毁。