基础篇:传递普通数据类型
MainActivity发送数据
Intent intent = new Intent(MainActivity.this,LoginActivity.class)
Bundle bundle = new Bundle()
bundle.putString("email","9110*076*@qq.com")
bundle.putString("password","123456")
intent.putExtras(bundle)
startActivity(intent)
LoginActivity接收数据(写在onCreate方法中)
Intent intent = getIntent()
Bundle bundle = intent.getExtras()
mEmailView.setText(bundle.getString("email"))
mPasswordView.setText(bundle.getString("password"))
进阶篇:传递自定义的类对象
1.用Serializable(不推荐:使用简单但效率低)
新建一个user类,implements Serializable
public class User implements Serializable{
private String email;
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String email,String password){
this.email = email;
this.password = password;
}
}
MainActivity发送数据
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
intent.putExtra("user",new User("9110*076*@qq.com","123456"));
startActivity(intent);
LoginActivity接收数据(写在onCreate方法中)
Intent intent = getIntent()
User user = (User)intent.getSerializableExtra("user")
2.用Parcelable(推荐:稍微复杂,android支持,效率高)
新建一个user类,implements Parcelable,实现两个未实现的方法
public class User implements Parcelable{
private String email;
private String password;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public User(String email,String password){
this.email = email;
this.password = password;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
Bundle bundle = new Bundle();
bundle.putString("email",getEmail());
bundle.putString("password",getPassword());
parcel.writeBundle(bundle);
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel parcel) {
Bundle userBundle = parcel.readBundle();
return new User(userBundle.getString("email"),userBundle.getString("password"));
}
@Override
public User[] newArray(int i) {
return new User[i];
}
};
}
MainActivity发送数据(相比第一种方法没有改变)
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
intent.putExtra("user",new User("9110*076*@qq.com","123456"));
startActivity(intent);
LoginActivity接收数据(写在onCreate方法中)
Intent intent = getIntent();
User user = intent.getParcelableExtra("user");