例子:MainAct传递参数至TheAty
方法一:
MainAty传递
i.putExtra("data","Hello jikexueyuan");
TheAty获取
private TextView tv ;
Intent i=getIntent();
tv= findViewById(R.id.tv);
方法二:Bundle传递
MainAty传递
Bundle b=new Bundle();
b.putString("name","jikexueyuan");
b.putInt("age",2);
i.putExtras(b);
TheAty获取
Bundle data=i.getExtras();
tv.setText(String.format("name=%s,age=%d,name1=%s",data.getString("name"),data.getInt("age"),data.getString("name1",
"leo")));
方法二延伸:
传递:
Bundle b=new Bundle();
b.putString("name","jikexueyuan");
b.putInt("age",2);
i.putExtra("data",b);
获取:
Bundle data=i.getBundleExtra("data");
传递值对象
分别由有两种方法:Parcelable及Serializable
其中Parcelable为较复杂但是速度较快,Serializalbe简单但是相对速度慢
Parcelable方法:
MainAty:
i.putExtra("user",new User("jikexueyuan",2));
startActivity(i);
TheAty:
private TextView tv ;
tv= findViewById(R.id.tv);
Intent i=getIntent();
User user =i.getParcelableExtra("user");
tv.setText(String.format("User info(name=%s,age=%d)",user.getName(),user.getAge()));
User:
public class User implements Parcelable { //parcelable接口,并且需添加两个方法,见下
private String name;
private int age;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public User(String name,int age){
this.name=name;
this.age=age;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getName());//写参数
dest.writeInt(getAge());
}
public static final CreatorCREATOR=new Creator() {
@Override
public User createFromParcel(Parcel source) {
return new User(source.readString(),source.readInt());
}
@Override
public User[] newArray(int size) {
return new User[size];
}
};//此处有分号
Serializable方法:
MainAty同上
TheAty:
private TextView tv;
tv= findViewById(R.id.tv);
Intent i=getIntent();
User user= (User) i.getSerializableExtra("user");
tv.setText(String.format("User info(name=%s,age=%d)",user.getName(),user.getAge()));
User:
public class User implements Serializable {
getset方法