27073205的专栏

Android中Bundle类的作用

Bundle类用作携带数据,

根据google官方的文档()

Bundle类是一个key-value对,“A mapping from String values to various Parcelable types.”

,它类似于

publicfinalclassBundleimplementsParcelable,Cloneable{

……

MapmMap;

publicBundle(){

mMap=newHashMap();

……

}

publicvoidputString(Stringkey,Stringvalue){

mMap.put(key,value);

}

publicStringgetString(Stringkey){

Objecto=mMap.get(key);

return(String)o;

……..//

}

}

类继承关系:

java.lang.Object android.os.BundleBundle类是一个final类:public final classBundleextends Objectimplements Parcelable Cloneable

在调用

一、API文档说明

  1.介绍

    用于不同Activity之间的数据传递

  1.重要方法

    clear():清除此Bundle映射中的所有保存的数据。

    clone():克隆当前Bundle

    containsKey(String key):返回指定key的值

    getString(String key):返回指定key的字符

    hasFileDescriptors():指示是否包含任何捆绑打包文件描述符

    isEmpty():如果这个捆绑映射为空,则返回true

    putString(String key, String value):插入一个给定key的字符串值

    readFromParcel(Parcel parcel):读取这个parcel的内容

    remove(String key):移除指定key的值

    writeToParcel(Parcel parcel, int flags):写入这个parcel的内容

两个activity之间的通讯可以通过bundle类来实现,做法就是:

1)新建一个bundle类

[java]view plain

(2)bundle类中加入数据(key -value的形式,,另一个activity里面取数据的时候,就要用到key,找出对应的value)

[java]view plain

(3)新建一个intent对象,并将该bundle加入这个intent对象

[cpp]view plain

intent.putExtras(mBundle);

代码实例:

例子1:

两个类如下:intent从TestBundle类发起,到Target类。

类1:TestBundle类

Intentintent=newIntent();BundlemBundle=newBundle();intent.putExtras(mBundle);startActivity(intent); 类2: TargetsetTitle(data); 例子2:

使用Bundle在Activity间传递数据

从源Activity 中传递数据

//数据写入IntentIntent openWelcomeActivityIntent=new Intent();Bundle myBundelForName=new Bundle();myBundelForName.putString("Key_Name",inName.getText().toString());myBundelForName.putString("Key_Age",inAge.getText().toString());openWelcomeActivityIntent.putExtras(myBundelForName);openWelcomeActivityIntent.setClass(AndroidBundel.this, Welcome.class);startActivity(openWelcomeActivityIntent);

目标Activity 中获取数据

//从Intent 中获取数据Bundle myBundelForGetName=this.getIntent().getExtras();String name=myBundelForGetName.getString("Key_Name");myTextView_showName.setText("欢迎您进入:"+name);

使用Bundle在Activity间传递数据2

从源请求Activity 中通过一个Intent 把一个服务请求传到目标Activity 中为我祈祷平安就好。我的旅行,会有你们的故事陪伴,所以我不会孤单。放心吧。

27073205的专栏

相关文章:

你感兴趣的文章:

标签云: