您的位置:首页 > 移动开发 > Android开发

Android中Bundle的使用

2016-08-23 14:28 148 查看
Bundle类是一个key-value对,“A mapping from String values to various Parcelable types.”
类继承关系:
java.lang.Object

     Android.os.Bundle

Bundle类是一个final类:

public final class

Bundle

extends Objectimplements Parcelable Cloneable

两个activity之间的通讯可以通过bundle类来实现,做法就是:
(1)新建一个bundle类

[java] view
plain copy

Bundle mBundle = new Bundle();   

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

[java] view
plain copy

mBundle.putString("Data", "data from TestBundle");
 

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

[cpp] view
plain copy

Intent intent = new Intent();    

intent.setClass(TestBundle.this, Target.class);    

intent.putExtras(mBundle);  

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

类1:TestBundle类:

[java] view
plain copy

import android.app.Activity;    

import android.content.Intent;    

import android.os.Bundle;    

import android.view.View;  

import android.view.View.OnClickListener;  

import android.widget.Button;  

  

public class TestBundle extends Activity {    

      

    private Button button1;  

    private OnClickListener cl;   

    public void onCreate(Bundle savedInstanceState) {    

        super.onCreate(savedInstanceState);    

        setContentView(R.layout.main);  

          

        button1 = (Button) findViewById(R.id.button1);  

        cl = new OnClickListener(){  

            @Override  

            public void onClick(View arg0) {  

                // TODO Auto-generated method stub  

                Intent intent = new Intent();    

                intent.setClass(TestBundle.this, Target.class);    

                Bundle mBundle = new Bundle();    

                mBundle.putString("Data", "data from TestBundle");//压入数据    

                intent.putExtras(mBundle);    

                startActivity(intent);  

            }  

        };  

        button1.setOnClickListener(cl);  

    }  

}    

类2: Target

[java] view
plain copy

import android.app.Activity;    

import android.os.Bundle;    

  

public class Target extends Activity{    

  

    public void onCreate(Bundle savedInstanceState) {    

          

        super.onCreate(savedInstanceState);    

        setContentView(R.layout.target);    

        <span style="color:#ff6600;">

        Bundle bundle = getIntent().getExtras();   

        </span> //得到传过来的bundle  

        String data = bundle.getString("Data");//读出数据    

        setTitle(data);    

  

    }    

}    

概况为以下几步:

1、实例化Bundle 一个对象,用putString(标记,数据)来将数据导入到Bundle对象中;  
2、然后将Bundle对象导入到Intent对象中;
3、Intent启动另一个activity。
4、Bundle对象可以从activity.getIntent().getExtras()中返回。可见,启动当前activity 
      的Intent对象是由getIntent()来找到的。
5、通过Bundle的getString()方法,就可以读出所要的数据。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息