Parcelable
和
Bundle
并不是互斥的概念;您甚至可以同时在您的应用程序上使用两者。术语
Parcelable
与Java中的序列化概念(以及其他高级语言,如C#,Python等)一起提供。它确保这样的
Parcelable
类的对象 - 仍留在RAM存储器中 - 可以保存在文件流(例如文本或内存)中,然后可以重构为在运行时(在线状态)中在程序中使用。
在一个Android应用程序中,在2个独立的activity之间(互斥运行,一个启动,另一个将停止):
当前 activity 没有指针来引用前一个活动及其成员 - 因为前一个活动已停止,并从内存中清除; 因此,为了保持传递给下一个活动的对象的值(从Intent调用),必须将对象设置为可Parcelable(可Serializable)。
虽然
Bundle
通常是指Android中的一个概念,用于表示一个变量或一组变量。如果我们深入看一下它的底层,它可以被认为是带有键值对的HashMap。
结论:
-
Bundle
用于存储许多具有相关键的对象,它可以保存任何原生类型的对象,但是它不知道如何保存一个复杂对象(例如包含ArrayList的对象)。
-
Parcelable
类用于确保其复杂实例在运行时可以进行序列化和反序列化。这个对象可以包含复杂类型,如ArrayList,HashMap,数组或结构体等。
public class NoneParcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public NoneParcelable()
{
nameList.add("abc");
nameList.add("xyz");
}
}
public class GoodParcelable implements Parcelable
{
private ArrayList<String> nameList = new ArrayList<String>();
public GoodParcelable()
{
nameList.add("Can");
nameList.add("be parsed");
}
@Override
public int describeContents()
{
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags)
{
}
}
在源活动中:
NoneParcelable nonePcl = new NoneParcelable();
GoodParcelable goodPcl = new GoodParcelable();
int count = 100;
Intent i = new Intent(...);
i.putExtra("NONE_P",nonePcl);
i.putExtra("GOOD_P",goodPcl);
i.putExtra("COUNT", count);
在目标活动中:
Intent i = getIntent();
NoneParcelable nP = (NoneParcelable)i.getExtra("NONE_P");
int count = (int)i.getExtra("COUNT");
GoodParcelable myParcelableObject=(GoodParcelable)i.getParcelableExtra("GOOD_P");
putExtra(String name, Serializable value)
方法。 - Squonk