1、直接使用intent携带数据
Intent intent = new Intent(this,SecondActivity.class);
//直接使用intent携带数据
intent.putExtra("date", "2016-11-23");
intent.putExtra("age", 22);
intent.putExtra("goShopping", true);
startActivity(intent);
获取数据
Intent intent = getIntent();
boolean flag = intent.getBooleanExtra("goShopping", false);
String date = intent.getStringExtra("date");
int age = intent.getIntExtra("age", 0);
2、使用Bundle携带数据
Intent intent = new Intent();
intent.setClass(this, SecondActivity.class);
Bundle bundle=new Bundle();
bundle.putBoolean("go_out", true);
bundle.putCharSequence("time", "11:06");
ArrayList<String>list=new ArrayList<String>();
list.add("A_a");
list.add("B_b");
list.add("C_c");
bundle.putStringArrayList("datas", list);
intent.putExtras(bundle);
startActivity(intent);
接收数据
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
boolean flag = bundle.getBoolean("go_out");
String date = bundle.getString("time");
ArrayList<String> datas = bundle.getStringArrayList("datas");
3、接收回传数据
在MainActivity.java中
Intent intent=new Intent(this,ContentActivity.class);
//requestCode 设置为6,并跳转至ContentActivity
startActivityForResult(intent, 6);
用onActivityResult方法接收
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(requestCode==6&&resultCode==0){
Toast.makeText(this, data.getStringExtra("name"), Toast.LENGTH_LONG).show();
}
}
在ContentActivity.java设置回传数据
public class ContentActivity extends Activity {
private ListView lv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
lv=(ListView) findViewById(R.id.lv);
final String[]datas=new String[]{"A","B","C","D","E"};
lv.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,datas));
lv.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Intent intent=new Intent();
intent.putExtra("name", datas[position]);
//resultCode=0 标记是哪个返回的数据
//intent 携带数据
setResult(0, intent);
//关闭activity
finish();
}
});
}
}
效果图