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

一:首先图示:

二:代码:

1:方法selectName

[java][/java]
  1. public void selectName(View view){
  2.         Intent intent = new Intent(this,NameListActivity.class);
  3.         startActivityForResult(intent, 1);
  4.     }
  5.     public void selectName2(View view){
  6.         Intent intent = new Intent(this,NameListActivity.class);
  7.         startActivityForResult(intent, 2);
  8.     }

2:方法setResult 与 finish();

[java][/java]
  1. lv_name.setOnItemClickListener(new OnItemClickListener(){
  2.     public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
  3.         String clickedName = names[position];
  4.         Toast.makeText(getApplicationContext(), clickedName, 0).show();
  5.         Intent data = new Intent();
  6.         data.putExtra(“clickedName”, clickedName);
  7.         setResult(0,data);
  8.         finish();
  9.     }
  10. });

3:方法onActivityResult

 

[java][/java] view plaincopyprint?

  1. protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  2.     super.onActivityResult(requestCode, resultCode, data);
  3.     if(data!=null){
  4.         String name = data.getStringExtra(“clickedName”);
  5.         if(requestCode == 1)
  6.             et_name.setText(name);
  7.         if(requestCode == 2)
  8.             et_name2.setText(name);
  9.     }
  10. }

标签