Intent传递对象,有两种方法
1. 实现Serializable接口
类要生成序列化ID,并且不能是内部类
2. 实现Parcelable接口
参照Parcelable的doc文档
实现Serializable接口的代码如下:
public class Person implements Serializable
{
private static final long serialVersionUID = -4520602519989894109L;
String name;
String age;
public Person(String name, String age)
{
super();
this.name = name;
this.age = age;
}
@Override
public String toString()
{
return "Person [name=" + name + ", age=" + age + "]";
}
}
从A启动B,通过intent传递person对象过去
private void startNewActivity()
{
Intent intent = new Intent();
intent.setClass(MainActivity.this, SecondActivity.class);
String name = etname.getText().toString();
String age = etage.getText().toString();
//用intent传递对象,那个类要实现序列化接口
Person person = new Person(name, age);
intent.putExtra(constant.PERSON, person);
startActivity(intent);
}
在B中得到A传过来的对象
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView textView = (TextView) findViewById(R.id.textView1);
Intent intent = getIntent();
Person person = (Person) intent.getSerializableExtra(constant.PERSON);
textView.setText(person.toString());
}
实现Parcelable接口的代码如下:
public class Person implements Parcelable
{
String name;
String age;
// 参照Parcelable的doc文档
public int describeContents()
{
return 0;
}
public void writeToParcel(Parcel out, int flags)
{
out.writeString(name);// 写跟下面的读顺序要一样
out.writeString(age);
}
public static final Parcelable.Creator<Person> CREATOR = new Parcelable.Creator<Person>()
{
public Person createFromParcel(Parcel in)
{
return new Person(in);
}
public Person[] newArray(int size)
{
return new Person[size];
}
};
public Person(String name, String age)
{
super();
this.name = name;
this.age = age;
}
public Person(Parcel in)
{
name = in.readString();// 读跟上面的写顺序要一样
age = in.readString();
}
@Override
public String toString()
{
return "Person [name=" + name + ", age=" + age + "]";
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Person other = (Person) obj;
if (age == null)
{
if (other.age != null)
return false;
}
else if (!age.equals(other.age))
return false;
if (name == null)
{
if (other.name != null)
return false;
}
else if (!name.equals(other.name))
return false;
return true;
}
}
在B中得到从A传来的对象
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
TextView textView = (TextView) findViewById(R.id.textView1);
Intent intent = getIntent();
Person person = (Person) intent.getParcelableExtra(constant.PERSON);
textView.setText(person.toString());
}
转载于:https://blog.51cto.com/wangcuijing/1275714