概述
1. 基本数据类型
存数据:
Intent it = new Intent(this, SecondActivity.class);
XXX value = xxx;
it.putExtra("key", value);
startActivity(it);
取数据:
int value = getIntent().getXXXExtra("key");
例如:
存数据:
Intent it = new Intent(FirstActivity.this, SecondActivity.class);
int value = 2;
it.putExtra("key", value);
startActivity(it);
取数据:
int value = getIntent().getIntExtra("key");
2. Bundle
存数据:
Intent it = new Intent(FirstActivity.this, SecondActivity.class);
Bundle bd = new Bundle();
bd.putInt("num", 1);
bd.putString("detail", "hello");
it.putExtras(bd);
startActivity(it);
取数据:
Bundle bd = getIntent().getExtras();
int value = bd.getInt("num");
String str = bd.getString("detail");
3. Serializable和Parcelable
3.1 Serializable
Person定义:
public class Person implements Serializable{
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}
存数据:
Person person = new Person();
person.setName("Tom");
person.setAge(20);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("person_data", person);
startActivity(intent);
取数据:
Person person = (Person) getIntent().getSerializableExtra("person_data");
3.2 Parcelable
Person定义:
public class Person implements Parcelable{
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
//这里的读的顺序必须与writeToParcel(Parcel dest, int flags)方法中写的顺序一致
public Person(String name, int age) {
super();
this.name = name;
this.age = age;
}
public Person() {
super();
}
//这里的读的顺序必须与writeToParcel(Parcel dest, int flags)方法中写的顺序一致,否则数据会有差错
public Person(Parcel source) {
name = source.readString();
age = source.readInt();
}
//这里默认返回0即可
@Override
public int describeContents() {
return 0;
}
//把值写入Parcel中
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(age);
}
public static final Creator<Person> CREATOR = new Creator<Person>() {
//供外部类反序列化本类数组使用
@Override
public Person[] newArray(int size) {
return new Person[size];
}
//从Parcel中读取数据
@Override
public Person createFromParcel(Parcel source) {
return new Person(source);
}
};
}
存数据://和Serializable相同
Person person = new Person();
person.setName("Tom");
person.setAge(20);
Intent intent = new Intent(FirstActivity.this, SecondActivity.class);
intent.putExtra("person_data", person);
startActivity(intent);
取数据://和Serializable的区别是函数名不同
Person person = (Person) getIntent().getParcelableExtra("person_data");
好文:https://www.jianshu.com/p/1169dba99261
最后
以上就是体贴招牌为你收集整理的Android系统之Intent传递数据的类型的全部内容,希望文章能够帮你解决Android系统之Intent传递数据的类型所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复