2011-08-05 59 views

回答

4

製作YourObject實現Parcelable接口,然後使用bundle.putParcelableArraylist(theParcelableArraylist)

編輯:哎喲誤讀了這個問題。爲什麼要保存一個ArrayList數組?如果它堅持改變方向,也許你想用onRetainNonConfigurationInstance代替?

編輯2:好的,在這裏。創建一個新的Wrapper類,實現Parcelable(注意,myObjects也必須是可以分類的)。該writeToParcel方法會是這個樣子:

public void writeToParcel(Parcel dest, int flags) { 
    dest.writeInt(mElements.length); 
    for(ArrayList<MyObject> element : mElements) { 
    dest.writeParcelableArray(element.toArray(new MyObject[0]), flags); 
    } 
} 

而且構造:

private Wrapper(Parcel in) { 
    int length = in.readInt(); 
    //Declare list 
    for (int i = 0; i < length; i++) { 
    MyObject[] read = in.readParcelableArray(Wrapper.class.getClassLoader()); 
    //add to list 
    } 
} 
+0

它主要是爲取向的改變,但我需要它,以及以適應活動的生命週期。 – Greg

+0

我認爲你可以創建一個實現parcelable的包裝類,並以一種不太優雅的方式來實現它。我會編輯我的答案。 – dmon

+0

你有這個工作嗎? –

0

如果你的對象支持序列化,標有Serializable接口,那麼你應該能夠使用bundle.putSerializable

ArrayList支持Serializable,但我不確定一個普通的array

1

不可能使用束,一束作爲僅允許原語的數組列表...

嘗試使用parcleable或應用程序級的數據或靜態變量(糟糕的做法)。

0

我只是用putSerializable(myarraylistofstuff),然後我回去使用get()一個演員,你只需要沉默未檢查警告。我懷疑(糾正我,如果錯誤),你可以通過任何僞裝它的對象作爲Serializable,只要你保持在同一個進程中它將通過對象引用。將數據傳遞給另一個應用程序時,這種方法顯然不起作用。

編輯:目前的Android只傳遞片段之間的參考,我試着任意對象傳遞給一個Activity,它的工作,但對象是不同的,使用的Fragment參數相同的測試表明相同Object代替。

反正它反序列化和序列化精我Object,如果你有大量的對象,最好使用Parcel代替