返回Acitivity时传递数据

返回Acitivty时需要传递数,有以下几个关键地方
  • startActivityForResult(intent, SMS_LIST); 告诉系统,这个activity:ContactActivity.class销毁时,会返回数据
  • onActivityResult 方法的监听
  • setResult(1, data);
// MainActivity.java
public class MainActivity extends Activity {
    static final int CONTACT_LIST = 10;
    static final int SMS_LIST = 20;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void click(View v) {
        Intent intent = new Intent(this, ContactActivity.class);
        // startActivity(intent);
        // 告诉系统,这个activity:ContactActivity.class销毁时,会返回数据
        startActivityForResult(intent, CONTACT_LIST);
    }
    public void quick(View v) {
        Intent intent = new Intent(this, SMSActivity.class);
        // startActivity(intent);
        // 告诉系统,这个activity:ContactActivity.class销毁时,会返回数据
        startActivityForResult(intent, SMS_LIST);
    }
    // 当一个应用返回数据的activity被销毁了,此方法会调用,用户接收数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        EditText et;
        if (requestCode == CONTACT_LIST) {
            et = (EditText) findViewById(R.id.et);
            et.setText(data.getStringExtra("name"));
        }
        if (requestCode == SMS_LIST) {
            et = (EditText) findViewById(R.id.content_et);
            et.setText(data.getStringExtra("content"));
        }
    }
}  
// ContactAcitivity.java
    // 虚构几个联系人
    String[] objects = new String[] { "芙蓉", "四大皆空", "梅西", "傻逼" };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);
        ListView listView = (ListView) findViewById(R.id.lv);
        listView.setAdapter(new ArrayAdapter(this,
                R.layout.item_contact, R.id.tv, objects));
        // 对ListView设置点击监听,我们需要知道用户什么时候点击了条目,还要知道用户点击的条目
        listView.setOnItemClickListener(new OnItemClickListener() {
            // 用户点击了哪一个条目,通过这个参数知道
            @Override
            public void onItemClick(AdapterView parent, View view,
                    int position, long id) {
                String text = objects[position];
                Intent data = new Intent();
                data.putExtra("name", text);
                // Activity一旦被销毁,这个data就会传到activity的调用者
                setResult(0, data);
                finish();
            }
        });
    }
}
//activity_main.xml

    
        
        
// activity_contact.xml


    
  
// item_contact.xml


    
  

你可能感兴趣的:(返回Acitivity时传递数据)