一:通过Serializable接口
public class User implements Serializable {
private static final long serialVersionUID = 2923551487809150124L;
public int userId;
public String name;
public boolean isMale;
@Override
public String toString() {
// TODO Auto-generated method stub
return "userId="+userId+";name="+name+";isMale="+isMale;
}
}
Activity中传递对象
User user = new User();
user.name="liming";
user.userId=1;
user.isMale=true;
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
Bundle mBundle = new Bundle();
mBundle.putSerializable("user",user);
intent.putExtras(mBundle);
startActivity(intent);
Activity中接收对象
User user = (User)getIntent().getSerializableExtra("user");
二:通过Parcelable接口实现
public class NewUser implements Parcelable {
public int userId;
public String userName;
public boolean isMale;
public NewUser() {
}
public NewUser(int userId, String userName, boolean isMale) {
this.userId = userId;
this.userName = userName;
this.isMale = isMale;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel out, int flags) {
// TODO Auto-generated method stub
out.writeInt(userId);
out.writeString(userName);
out.writeInt(isMale ? 1 : 0);
}
public static final Parcelable.Creator<NewUser> CREATOR = new Parcelable.Creator<NewUser>() {
public NewUser createFromParcel(Parcel in) {
return new NewUser(in);
}
public NewUser[] newArray(int size) {
return new NewUser[size];
}
};
private NewUser(Parcel in) {
userId = in.readInt();
userName = in.readString();
isMale = in.readInt() == 1;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "userId=" + userId + ";name=" + userName + ";isMale=" + isMale;
}
}
Activity中传递对象
NewUser user = new NewUser();
user.isMale = false;
user.userId = 1;
user.userName = "jack";
Intent mintent = new Intent(SecondActivity.this,ThirdActivity.class);
Bundle mBundle = new Bundle();
mBundle.putParcelable("newuser",user);
mintent.putExtras(mBundle);
startActivity(mintent);
Activity中接收对象
NewUser user = (NewUser)getIntent().getParcelableExtra("newuser");