标签:
传递简单数据
//发送方
i.putExtra("data",t.getText().toString());
//接收方
Intent i = getIntent();
m = (EditText)findViewById(R.id.et2);
m.setText(i.getStringExtra("data"));
数据回传
//接收方
public void sendBack(View view){
Intent i = new Intent();//不仅可以跳转activity,还可以作为数据的载体传递)
i.putExtra("data",m.getText().toString());
setResult(1,i);//设置responseCode为1
finish();//结束当前activity
}
//发送方
startActivityForResult(i,0);//设置requestCode为0
/***重写方法onActivityResult(),通过requestCode和resultCode来识别本次StartActivity的意义***/
protected void onActivityResult(int requestCode, int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
n.setText("另外一个activity返回的数据是:"+ data.getStringExtra("data"));
}
使用bundle传递数据包
//发送方
Bundle b = new Bundle();
b.putString("Name","lin");
b.putInt("Age",17);
b.putInt("Classid",3);
i.putExtras(b);
//接收方
Bundle b = i.getExtras();
m.setText(String.format("Name:%s,Age:%d,Classid:%d",b.getString("Name"),b.getInt("Age"),b.getInt("Classid")));
传递值对象
传递值对象有两种方式(serializable和parcelable)
①serializable (序列化过程由系统完成,速度较慢)
//新建User类
public class User implements Serializable {}
//发送方
i.putExtra("user",new User(2,"duolaAmeng"));
//接收方
User u = (User) i.getSerializableExtra("user");
m.setText(String.format("user info(name=%s,age=%d)",u.getName(),u.getAge()));
②parcelable (专门针对android平台,没有采用系统的序列化机制,速度较快)
//新建User类
public class User implements Parcelable {
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(getName());
parcel.writeInt(getAge());
}
public static final Creator<User> CREATOR = new Creator<User>() {
@Override
public User createFromParcel(Parcel parcel) {
return new User(parcel.readInt(),parcel.readString());
}
@Override
public User[] newArray(int i) {
return new User[i];
}
};
//接收方
User u = (User) i.getParcelableExtra("user");
m.setText(String.format("user info(age=%d,name=%s)",u.getAge(),u.getName()));
BUT: parcelable方法可运行成功,但结果不对,"name"传null,“age"传10,后续跟进。
注:①什么是序列化?什么时候需要使用序列化?
②Creator<User> ?
标签:
原文地址:http://www.cnblogs.com/biang/p/5689039.html