android参数传递的几种方法
Intent
Intent i=new Intent(当前Activity.this,目标Activity.class);
1.传单值
传入:
i. i.putExtra("名称","数据类型");
startActivity(i)
接收:
Intent i=getIntent();
String val=i.getStringExtra("名字");
2.传Bunlde对象
传入:
(1)
Bunlde b=new Bunlde();
b.putString("键值名称","键值");
i. i.putExtra(b);
(2)
i. i.putExtra("名称",b);
接收:
Intent i=getIntent();
(1)
Bunlde data=i.getExtras();
(2)
Bunlde data=i.getBunldeExtra("名称");
String val=data.getString("键值名称");
//键值不存在的时候,赋默认值
String val=data.getString("键值名称","默认值");
3.传Model对象
方式一:Serializable:
传入:
public class UserModel implements Serializable{}
i.putExtra("user", new UserModel(strAccount,"test",1));
接收:
UserModel user=(UserModel)i.getSerializableExtra("user");
String userName=user.getUserName();
方式二:Parcelable:
public class UserModel implements Parcelable {
protected UserModel(Parcel in) {
UserId = in.readInt();
UserName = in.readString();
Account = in.readString();
}
public static final Creator<UserModel> CREATOR = new Creator<UserModel>() {
@Override
public UserModel createFromParcel(Parcel in) {
return new UserModel(in.readString(),in.readString(),in.readInt());
}
@Override
public UserModel[] newArray(int size) {
return new UserModel[size];
}
};
private int UserId;
public int getUserId() {return UserId;}
public void setUserId(int userId) {this.UserId = userId;}
private String UserName;
public String getUserName() {return UserName;}
public void setUserName(String userName) {this.UserName = userName;}
private String Account;
public String getAccount() {return Account;}
public void setAccount(String account) {this.Account = account;}
public UserModel(String strAccount,String strUserName,int id){
this.Account=strAccount;
this.UserId=id;
this.UserName=strUserName;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(getAccount());
dest.writeString(getUserName());
dest.writeInt(getUserId());
}
}
传入:
i.putExtra("user", (Parcelable) new UserModel(strAccount,"test",1));
接收:
UserModel user=(UserModel)i.getParcelableExtra("user");
String userName=user.getUserName();
4.传返回值
1.需要返回的界面
Intent i=new Intent();
i. i.putExtra("名称","数据类型");
setResult(1,i);
finish();
2.返回界面接收值
startActivityForResult(i,0);//第一个为数据参数,第二个为请求代码参数
加下面方法
@Override
//requestCode:请求代码
//resultCode:返回的结果码
//data:返回的结果数据
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//处理返回回来的数据。
}
终身学习,系统学习。