Activity之间的传值
2016-11-01 本文已影响314人
sunshinesuns
第一种方式使用Intent
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("name","zhangsan");
startActivity(intent);
//接收数据
Intent intent = getIntent();
String value = intent.getStringExtra("name");
TextView textView = (TextView)findViewById(R.id.textView1);textView.setText(value);
第二种方式使用Intent结合Bundle
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
Bundle b = new Bundle();
b.putString("name","李四"); b.putInt("age",30);
intent.putExtras(b);
startActivity(intent);
//接收数据
Intent intent = getIntent();Bundle data = intent.getExtras();
TextView textView = (TextView)findViewById(R.id.textView1);textView.setText(String.format("name=%s,age=%d",data.getString("name"),data.getInt("age")));
第三种方式传值,传自定义对象实现(实现Serializable接口,性能较差,系统自动处理)
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("user",new User("linqin",30));
startActivity(intent);
//接收数据
Intent intent = getIntent();
User user = (User)intent.getSerializableExtra("user");
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText(String.format("User info name = %s,age=%d",user.getName(),user.getAge()));
//对象代码
public class User implements Serializable {
private String name;
private Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(String name,Integer age){
this.name = name;
this.age = age;
}
}
第四种种方式传值,传自定义对象(实现Parcelable接口,性能较好)
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("user",new User("linqin",30));
startActivity(intent);
//接收数据
Intent intent = getIntent();
User user = (User)intent.getParcelableExtra("user");
TextView textView = (TextView)findViewById(R.id.textView1);
textView.setText(String.format("User info name = %s,age=%d",user.getName(),user.getAge()));
//对象代码
public class User implements Parcelable {
private String name;
private Integer age;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(String name,Integer age){
this.name = name;
this.age = age;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
//多个同类型属性使用Bundle
dest.writeString(getName());
dest.writeInt(getAge());
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel source) {
return new User(source.readString(),source.readInt());
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};
}