Activity之间的数据传递分为:
1、直接使用Intent的putExtra进行不同类型的数据进行传递。
Intent intent=new Intent(FifstActivity.this,SecondActivity.class);
intent.putExtra("test","text");
startActivity(intent);
Intent intent=getIntent();
String string=intent.getStringExtra("test");
Toast.makeText(getBaseContext(), "" +string, Toast.LENGTH_SHORT).show();
2、使用Serializable传递一个可序列化的数据集合
EditText username = (EditText) findViewById(R.id.username);
EditText passwd = (EditText) findViewById(R.id.passwd);
RadioButton sex = (RadioButton) findViewById(R.id.male);
String gender = sex.isChecked() ? "男" : "女";
Person p=new Person(username.getText().toString(),passwd.getText().toString(),gender);
Bundle data=new Bundle();
data.putSerializable("person",p);
Intent intent=new Intent(FifstActivity.this,SecondActivity.class);
intent.putExtras(data);
startActivity(intent);
但是使用这种方式,那么数据类Person就必须继承Serializable这个接口。
class Person implements Serializable
然后在需要使用数据的地方直接通过Key来获取值就可以了。
Intent intent=getIntent();
Person p=(Person) intent.getSerializableExtra("person");
Toast.makeText(getBaseContext(), "" + p.getUsername() + p.getPasswd() + p.getSex(), Toast.LENGTH_SHORT).show();