本篇文章來源於 Linux公社網站(www.linuxidc.com) 原文連結:http://www.linuxidc.com/Linux/2012-04/58732.htm
一、傳遞List<String>和List<Integer>
以下以傳遞List<String>為例,發送List<String>文法為:
intent.putStringArrayListExtra(key, list);
接收List<String>的文法為:
list = (ArrayList<String>)getIntent().getStringArrayListExtra(key);
以下是一個運用執行個體:
// =============發送List<String>=============
ArrayList<String> stringList = new ArrayList<String>();
stringList.add("string1");
stringList.add("string2");
stringList.add("string3");
Intent intent = new Intent();
intent.setClass(ListDemoActivity.this, StringListActivity.class);
intent.putStringArrayListExtra("ListString", stringList);
startActivity(intent);
// ====================接收List<String>======================
ArrayList<String> stringList = (ArrayList<String>) getIntent().getStringArrayListExtra("ListString");
List<Integer>類似以上的操作調用下面的方法也可以實現發送和接收:
intent.putIntegerArrayListExtra(key, list);
list =(ArrayList<Integer>) getIntent().getIntegerArrayListExtra(key);
二、使用Serializable和Parcelable兩種方式傳遞Object
Android的Intent之間傳遞對象有兩種方法,一種是Bundle.putSerializable(Key,Object);另一種是Bundle.putParcelable(Key,Object)。方法中的Object要滿足一定的條件,前者實現了Serializable介面,而後者實現了Parcelable介面。
以下是實現了Serializable介面的User類,命名為SerializableUser純粹是從類名方便區分實現了Parcelable介面的User類,實際開發中不建議這麼命名:
public class SerializableUser implements Serializable {
private String userName;
private String password;
public SerializableUser() {
}
public SerializableUser(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
以下是實現了Parcelable介面的User類:
public class ParcelableUser implements Parcelable {
private String userName;
private String password;
public ParcelableUser() {
}
public ParcelableUser(String userName, String password) {
this.userName = userName;
this.password = password;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static final Parcelable.Creator<ParcelableUser> CREATOR = new Creator<ParcelableUser>() {
@Override
public ParcelableUser createFromParcel(Parcel source) {
ParcelableUser parcelableUser = new ParcelableUser();
parcelableUser.userName = source.readString();
parcelableUser.password = source.readString();
return parcelableUser;
}
@Override
public ParcelableUser[] newArray(int size) {
return new ParcelableUser[size];
}
};
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(userName);
dest.writeString(password);
}
}
使用兩種方式傳遞的文法分別為:
bundle.putSerializable(key,object);
bundle.putParcelable(key,object);
使用兩種方式接收的文法分別為:
object=(Object) getIntent().getSerializableExtra(key);
object=(Object) getIntent().getParcelableExtra(key);
// ==========分別使用Serializable和Parcelable發送Object===============
SerializableUser serializableUser = new SerializableUser("user1", "123456");
ParcelableUser parcelableUser = new ParcelableUser("user2","654321");
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putSerializable("serializableUser", serializableUser);
bundle.putParcelable("parcelableUser", parcelableUser);
intent.setClass(ListDemoActivity.this,ObjectActivity.class);
intent.putExtras(bundle);
startActivity(intent);
// ====================接收Object======================
SerializableUser serializableUser = (SerializableUser) getIntent().getSerializableExtra("serializableUser");
ParcelableUser parcelableUser = (ParcelableUser) getIntent().getParcelableExtra("parcelableUser");
可能有人注意到,實現Serializable介面就是把對象序列化,然後再傳輸,和Java的常用編程沒什麼明顯區別,而且User不需要明顯改變,比較簡單。我也推薦用這種方式。
然而,後一種實現Parcelable介面的類比較複雜,Parcelable是個什麼東西呢?
Android提供了一種新的類型:Parcel,被用作封裝資料的容器,封裝後的資料可以通過Intent或IPC傳遞。 除了基本類型以外,只有實現了Parcelable介面的類才能被放入Parcel中。
實現Parcelable介面需要實現三個方法:
1)writeToParcel 方法。該方法將類的資料寫入外部提供的Parcel中。
聲明:writeToParcel (Parcel dest, int flags)。
2)describeContents方法。直接返回0就可以。
3)靜態Parcelable.Creator<T>介面,本介面有兩個方法:
createFromParcel(Parcel in) 實現從in中建立出類的執行個體的功能。
newArray(int size) 建立一個類型為T,長度為size的數組, returnnew T[size];即可。本方法是供外部類還原序列化本類數組使用。
通過log測試輸出可知程式的運行情況,在bundle.putParcelable(“parcelableUser”, parcelableUser);時,調用了ParcelableUser類中的publicvoid writeToParcel(Parcel dest, int flags)方法,並向dest寫資料,在 ParcelableUserparcelableUser= (ParcelableUser)getIntent().getParcelableExtra(“parcelableUser”);的時候,調用了ParcelableUser類中的public ParcelableUsercreateFromParcel(Parcel source) 方法,建立了一個ParcelableUser對象,並給這個對象的屬性賦值,這裡的Parcel source和Parcel dest是相同的,然後返回這個ParcelableUser對象。最後就可以列印出parcelableUser的屬性資訊了。
三、傳遞List<Object>
如果我們要傳遞的是Object組成的List列表,即List<Object>,該怎麼辦呢?首先需要將Object對象實現Serializable介面,然後把list強制類型轉換成Serializable類型,最後通過:
Intent.putExtra(key, (Serializable)objectList);
這樣的文法來傳遞,接收方在接收的時候也需要強制類型轉換成List<Object>,接收 List<Object>使用的文法是:
objectList= (List<Object>) getIntent().getSerializableExtra(key);
以下是一個應用執行個體,這裡使用的SerializableUser類在上一步有給出,這裡就不再重複給出。
// ==============發送List<Object>===========
SerializableUser user1 = new SerializableUser("user1", "123456");
SerializableUser user2 = new SerializableUser("user2", "654321");
List<SerializableUser> objectList = new ArrayList<SerializableUser>();
objectList.add(user1);
objectList.add(user2);
Intent intent = new Intent();
intent.setClass(ListDemoActivity.this, ObjectListActivity.class);
intent.putExtra("ListObject", (Serializable) objectList);
startActivity(intent);
// ====================接收List<Object>======================
List<SerializableUser> objectList = (List<SerializableUser>) getIntent().getSerializableExtra("ListObject");
四、全域變數
如果一些特殊的應用層級的參數,不方便使用intent來傳遞參數,我們很容易想到是不是有全域變數或靜態變數可以使用?Java中的靜態變數在這裡是適合的,但其值在Activity調用了System.exit(0)或finish()後就丟失了。
而在android中有個更優雅的方式是使用ApplicationContext。這種全域變數方法相對靜態類更有保障,直到應用的所有Activity全部被destory掉之後才會被釋放掉。
Android的SDK中有說道,Application是用來儲存全域變數的,並且是在package建立的時候就存在了。所以當我們需要建立全域變數的時候,不需要再像J2SE那樣需要建立public許可權的static變數,而直接在application中去實現。只需要調用Context的 getApplicationContext或者Activity的getApplication方法來獲得一個Application對象,就可以設定或讀取全域變數的值。
啟動Application時,系統會建立一個PID,即進程ID,所有的Activity就會在此進程上運行。那麼我們在Application建立的時候初始化全域變數,同一個應用的所有Activity都可以取到這些全域變數的值,換句話說,我們在某一個Activity中改變了這些全域變數的值,那麼在同一個應用的其他Activity中值就會改變。
用法:
1. 建立一個屬於你自己的android.app.Application的子類,為想要共用的private全域變數增加setter和getter方法。
public class MyApp extends Application{
private String globalVariable;
public String getGlobalVariable() {
return globalVariable;
}
public void setGlobalVariable(String globalVariable) {
this.globalVariable = globalVariable;
}
}
2. 在manifest中申明一下這個類,這時Android就為此建立一個全域可用的執行個體。
其實就是在原來僅有的一個application標籤上為application制定一個名字為這個全域執行個體。
<application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name">
3. 可以在其他任何地方使用Context.getApplicationContext()方法擷取這個執行個體,進而擷取其中的狀態(變數)。
// ============使用全域變數傳遞參數==============
MyApp myApp = ((MyApp) getApplicationContext());//獲得我們的應用程式MyApp
myApp.setGlobalVariable("全域變數");
Intent intent = new Intent();
intent.setClass(ListDemoActivity.this, GlobalActivity.class);
startActivity(intent);
// ============接收全域變數的參數==============
MyApp myApp = ((MyApp) getApplicationContext());
String globalVariable = myApp.getGlobalVariable();
通過上述關於傳遞Object對象、List類型、List<Object>類型和全域變數等的介紹,希望能夠給大家提供一些協助。
本篇文章來源於 Linux公社網站(www.linuxidc.com) 原文連結:http://www.linuxidc.com/Linux/2012-04/58732.htm