android---Activity间消息互传

当一个Activity1开启一个新的Activity2时,可以将一个Bundle对象绑定在Intent中进行传递,而Bundle对象中可以存储很多种类型的数据,支持的数据类型有int、string、ArrayList、List、boolean、byte、char等等,如果关闭Activity2返回Activity1时要传递数据,则Activity1需以startActivityForResult(intent,requestCode)方式开启Activity2,并且Axtivity2设置setResult(RESULT_OK, intent),这样当关闭Activity2时,就会触发Activity的回调函数onActivityResult();

完整代码如下:

Activity1

代码
 
   
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

btnjump
= (Button)findViewById(R.id.btnload);
btnjump.setOnClickListener(
this );
etname
= (EditText)findViewById(R.id.actname);
etpwd
= (EditText)findViewById(R.id.etpwd);
}

// 被此Activity启动的Activity返回结果时触发的回调函数
@Override
public void onActivityResult( int requestCode, int resultCode, Intent data){
if (resultCode == RESULT_OK){
Bundle bundle
= data.getExtras();
Toast.makeText(
this , bundle.getString( " name " ) + " / " + bundle.getString( " pwd " ), Toast.LENGTH_LONG);
}
super.onActivityResult(requestCode, resultCode, data);
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String name = etname.getText().toString();
String pwd
= etpwd.getText().toString();
Intent intent
= new Intent();
Bundle bundle
= new Bundle();
bundle.putString(
" name " , name);
bundle.putString(
" pwd " , pwd);
intent.putExtras(bundle);

// requestCode大于等于0,当返回Activity时,会回调onActivityResult()函数
int requestCode = 0 ;
// 启动一个Activity,并且被启动的Activity返回结果时会触发回调函数
this .startActivityForResult(intent,requestCode);
}

 

Activity2:

 

代码
 
   
public class TwoActivity extends Activity {

public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
this .setContentView(R.layout.two);
TextView tvshow
= (TextView)findViewById(R.id.tvShow);
Intent intent
= this .getIntent();
Bundle bundle
= intent.getExtras();
final String name
= bundle.getString( " name " );
final String pwd
= bundle.getString( " pwd " );
tvshow.setText(name
+ " / " + pwd);

Button btn
= (Button)findViewById(R.id.btnback);
btn.setOnClickListener(
new OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent data = new Intent();
Bundle extras
= new Bundle();
extras.putString(
" name " , " 返回: " + name );
extras.putString(
" pwd " , " 返回: " + pwd);
data.putExtras(extras);
TwoActivity.
this .setResult(RESULT_OK, data); // 返回数据
finish();
}
});
}
}

 

转载于:https://www.cnblogs.com/jico/archive/2010/11/01/1866483.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值