Android开发:向下一个activity传递数据,返回数据给上一个activity

时间:2023-12-25 11:25:19

1.向下一个activity传递数据

activity1

         Button button=(Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() { @Override
public void onClick(View v) {
Intent intent=new Intent("1111111111111111111");
intent.addCategory("android.intent.category.MY_CATEGORY");
intent.putExtra("aaa", "this is a message");
startActivityForResult(intent, 0x11);
}
});

activity2

1         Intent intent=getIntent();
String data=intent.getStringExtra("aaa");
Toast.makeText(activity2.this, data, Toast.LENGTH_SHORT).show();

2.返回数据给上一个activity

activity2,按钮实现返回到activity1

         Button jumpButton=(Button) findViewById(R.id.jumpButton);
jumpButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent=new Intent();
intent.putExtra("xxx", "This is second activity data!");
setResult(RESULT_OK,intent);
finish();
}
});

activity1

重写onActivityResult()

     @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==0x11) {
if (resultCode==RESULT_OK) {
returnData=data.getStringExtra("xxx");
}
}
}