Activity中的startActivityResult,setResult,finish,onActivityResult的关系

时间:2021-10-02 12:58:25

一:首先图示:

Activity中的startActivityResult,setResult,finish,onActivityResult的关系

二:代码:

1:方法selectName

public void selectName(View view){
Intent intent = new Intent(this,NameListActivity.class);
startActivityForResult(intent, 1);
}
public void selectName2(View view){
Intent intent = new Intent(this,NameListActivity.class);
startActivityForResult(intent, 2);
}

2:方法setResult 与 finish();

		lv_name.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
String clickedName = names[position];
Toast.makeText(getApplicationContext(), clickedName, 0).show();
Intent data = new Intent();
data.putExtra("clickedName", clickedName);
setResult(0,data);
finish();
}
});

3:方法onActivityResult

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(data!=null){
String name = data.getStringExtra("clickedName");
if(requestCode == 1)
et_name.setText(name);
if(requestCode == 2)
et_name2.setText(name); }
}