2

我想在活动之间发送一个对象。阅读此内容后,我得出结论,使用 Parcelable 是最好的方法,因为它对性能的影响最小。我想这样做的原因是因为我需要从网络下载数据来创建一个对象,所以我不想继续下载数据。

但是,为了使用 Parcel,该类需要实现 Parcelable。当我试图发送在库中定义的对象时,我无法编辑类以包含它。

解决我的困境的最佳方法是什么?

我尝试扩展库类并实现 Parcelable,但因 ClassCastException 而失败。我还看到提到我应该创建一个包裹我的库类的 Parcelable 类并以这种方式发送?

谢谢!

4

2 回答 2

0

使用parceler 库怎么样?你可以告诉你Application包裹图书馆类

@ParcelClass(LibraryParcel.class)
public class AndroidApplication extends Application{
    //...
}

如果可行,您可以使用以下代码来打包/解包:

Parcelable wrapped = Parcels.wrap(new Example("Andy", 42));
Example example = Parcels.unwrap(wrapped);
example.getName(); // Andy
example.getAge(); // 42
于 2018-06-06T10:18:55.110 回答
-1

您是否尝试使用Bundle

例如,如果您有 Parcelable 类 User

Bundle bundle = new Bundle();
List<User> users = new ArrayList<User>();
String userName = user.setUserName("some name");
boolean isOnline = user.setOnline(true);
users.add(user);
bundle.putParcelableArrayList("USER", users);

您可以将其检索为:

public ArrayList<User> getParcelableArrayList(Bundle bundle){
   List<User> userList = new ArrayList<User>();
   userList = bundle.getParcelableArrayList("USER");
}
于 2013-03-19T15:27:58.667 回答