FBI Warning:歡迎轉載,但請標明出處:http://blog.csdn.net/codezjx/article/details/8876753,未經本人同意請勿用於商業用途,感謝支持!
Intent傳遞基本類型相信大家都十分熟悉,如何傳遞Object對象或者ArrayList<Object>對象呢?
可以通過:
(1)public Intent putExtra (String name, Serializable value)
(2)public Intent putExtra (String name, Parcelable value)
public Intent putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)
一、通過實現Serializable接口傳遞
(1)首先讓Person繼承Serializable接口
package com.example.hellojni;
import java.io.Serializable;
public class Person implements Serializable{
/**
* Auto generate
*/
private static final long serialVersionUID = -5053412967314724078L;
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
(2)通過Intent來進行傳輸,具體方法是:public Intent putExtra (String name, Serializable value)
Intent intent = new Intent(this, OtherActivity.class);
intent.putExtra("person", new Person("bear", 22));
startActivity(intent);
Intent intent = getIntent();
Person person = (Person)intent.getSerializableExtra("person");
System.out.println("name:" + person.getName());
System.out.println("age:" + person.getAge());
(4)傳遞ArrayList<Person>:
Intent intent = new Intent(this, OtherActivity.class);
ArrayList<Person> personList= new ArrayList<Person>();
initList(personList); //初始化personList
intent.putExtra("personList", personList);
startActivity(intent);
(注意傳值類型必須是ArrayList而不能是List。調用的還是public
Intent putExtra (String name, Serializable value)這個函數,另外一邊獲取的時候強制轉化爲ArrayList<Person>即可)二、通過實現Parcelable接口傳遞
同上,Person類實現Parcelable接口即可:
傳遞Object用:public Intent putExtra (String name, Parcelable value)
傳遞ArrayList<Object>用:public Intent putParcelableArrayListExtra(String name, ArrayList<? extends Parcelable> value)
(同是序列化的接口,爲神馬Parcelable分開提供了2個函數,而傳Serializable只提供了一個?這裏我也很不解。。。)