在 Activity 间传递数据

Android Activity间数据传递
本文介绍如何使用Bundle在Android的Activity之间传递数据。包括从源Activity向目标Activity传递数据的方法,以及如何通过Intent请求和返回数据的过程。

在 Activity 间传递数据

使用 Bundle 在 Activity 间传递数据1

从源 Activity 中传递数据
      //数据写入 Intent                                       

 Intent 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 中
private Intent toNextIntent;//Intent 成员声明    

toNextIntent=new Intent();//Intent 定义

toNextIntent.setClass(TwoActivityME3.this SecondActivity3.class);      //设定开启的下一个Activity      

startActivityForResult(toNextIntent, REQUEST_ASK);//开启 Intent 时候,把请求码同时传递

在源请求 Activity 中等待 Intent 返回应答结果,通过重载 onActivityResult()方法

      @Override                                      

Protected void onActivityResult(int requestCode,int resultCode, Intent data) {   // TODO Autogenerated method stub          

super.onActivityResult(requestCode, resultCode, data);              

if (requestCode==REQUEST_ASK){            

if(resultCode==RESULT_CANCELED)              

setTitle("Cancel****"); 

else if(resultCode==RESULT_OK){         

showBundle=data.getExtras();//从返回的Intent中获得Bundle   

Name=showBundle.getString("myName");//从bundle中获得相应数据                  text.setText("the name get from the secondlayout:\n"+Name) ;             

}         

}     

}

第一个参数是你开启请求Intent时的对应请求码,可以自己定义。

第二个参数是目标Activity返回的验证结果码         

第三个参数是目标Activity返回的Intent

目标 Activity 中发送请求结果代码,连同源 Activity 请求的数据一同绑定到 Bundle中通过 Intent 传回源请求 Activity 中

new backIntent=new Intent();            

new stringBundle=new Bundle();         

stringBundle.putString("myName", Name);         

backIntent.putExtras(stringBundle);         

setResult(RESULT_OK, backIntent);//返回Activity结果码       

finish();

转载于:https://www.cnblogs.com/dengbozyz/archive/2010/08/15/1800253.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值