android传值

时间:2023-03-10 06:05:56
android传值

需求

OneActivity向TwoActivity传值name=hzs,然后TwoActivity向OneActivity传值sex=Y

第一步:OneActivity向TwoActivity传值name=hzs

OneActivity 里设置

Intent intent = new Intent(OneActivity.this,TwoActivity.class);
intent.putExtra("name","hzs");
startActivityForResult(intent,2008); //code是请求码 int类型

TwoActivity 里取值

Intent getIntent = getIntent();
String name = getIntent.getStringExtra("name");

第二步:TwoActivity向OneActivity传值sex=Y

TwoActivity 里设置

Intent intent = new Intent();
intent.putExtra("sex", "Y");
setResult(1, intent); //resultCode 为返回码 用于区分从哪里返回。
finish();

OneActivity 里取值

@Override 
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

switch(requestCode){

case 2000:

if(resultCode==1){

String sex = data.getStringExtra("sex");

}

break;

default:

}

super.onActivityResult(requestCode, resultCode, data); 
}