你的位置:首页 > 操作系统

[操作系统]Activity获取返回值


public class MainActivity extends Activity {  @Override  protected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);      }  public void click(View c){    //跳转至选择联系人Activity    Intent intent = new Intent(this, ContactActivity.class);//    startActivity(intent);    //用这个api启动的Activity,在销毁时,系统会回调onActivityResult    startActivityForResult(intent, 10);  }      //如果有Activity在销毁时返回了数据,那么就会调用此方法来接收数据  //requestCode:用来区分数据来自于哪一个Activity  //resultCode:用来区分返回的数据是什么类型的  @Override  protected void onActivityResult(int requestCode, int resultCode, Intent data) {    // TODO Auto-generated method stub    super.onActivityResult(requestCode, resultCode, data);        String name = data.getStringExtra("name");    if(requestCode == 10){      EditText et = (EditText)findViewById(R.id.et);      et.setText(name);    }      }  }

public class ContactActivity extends Activity {  @Override  protected void onCreate(Bundle savedInstanceState) {    // TODO Auto-generated method stub    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_contact);        ListView lv = (ListView) findViewById(R.id.lv);        final String[] objects = new String[]{        "小志",        "逼哥",        "世界级XXX",        "国服第一"    };        lv.setAdapter(new ArrayAdapter<String>(this, R.layout.item_listview, R.id.tv, objects));      //给listview设置条目的点击侦听    lv.setOnItemClickListener(new OnItemClickListener() {      //当某个条目被点击时,此方法调用      @Override      public void onItemClick(AdapterView<?> parent, View view,          int position, long id) {                //Activity返回时传递数据,也是通过意图对象        Intent data = new Intent();        //把要传递的数据封装至意图对象中        data.putExtra("name", objects[position]);                //当前Activity销毁时,data这个意图就会传递给启动当前Activity的那个Activity        setResult(1, data);                //销毁当前Activity        finish();      }    });  }    @Override  public void onBackPressed() {    // TODO Auto-generated method stub    super.onBackPressed();  }}