在Activity和Fragment之间传递对象时,是否发生序列化 [英] Does it ocurr serialization when passing objects between Activity's and Fragments
问题描述
我有一个类Crop
,当将其意图传递给另一个Activity
时,该类不可序列化.但是,如果它是从Activity
到Fragment
(波谷Bundles
)的对象,则没有错误,并且我可以看到另一面的drawable对象没有任何错误.
I have a class Crop
that isn't Serializable when it comes to passing her trough an intent to another Activity
. But if it is from an Activity
to a Fragment
(trough Bundles
), there's no error and I can see the drawable object in the other side with no errors whatsoever.
如何在一种情况下可序列化而在另一种情况下不能序列化?
How can it be serializable in one case but not in the other ?
public class Crop implements Serializable {
private String specieHarvest;
private String specieLocation;
private String specieName;
private Drawable img;
}
推荐答案
首先,让我们回答您的问题.
First, let's answer your question.
您看到的行为的原因是
- 将对象作为附加对象传递给
activity
,将始终导致该对象被Android封送/取消封送,这被认为是某种IPC. - 将对象作为参数传递给
fragment
并不会总是导致对象被封送.
- Passing objects as extras to an
activity
, will always cause that object to be marshaled/un-marshaled by Android, it is thought of as some kind of IPC. - Passing objects as arguments to a
fragment
will not always cause your object to be marshaled.
然后,何时将对象发送给片段将其分解并由Android重建?
除非被某种原因销毁并重新创建片段,否则不会被序列化/反序列化当您拨打getArguments().
It will not be serialized/de-serialized unless the fragment is destroyed and recreated for some reason, otherwise, that object is kept in a map and the same object is returned to you when you call getArguments().
如果甚至在Fragment
中更改该对象,它也会更改发送的原始对象,因为实际上是相同的引用.疯狂吧? :)
If you even change that object in the Fragment
, it will change the original one that was sent, because it is in fact the same reference. CRAZY, right? :)
如果您查看Drawable
类,您会发现它不是Parcelable
或Serializable
,所以请不要在意图/参数中传递它.
If you take a look at Drawable
class, you will find that it is not Parcelable
or Serializable
, so don't pass it along in intents/arguments.
相反,如果资源中包含Drawable
对象,则传递一个int,该int可以是资源ID;如果该图像是本地存储在某个地方的图像,则可以传递String
路径.
Instead, pass an int which can be the resource ID if the Drawable
object is in your resources, or you can pass a String
path if that is an image that is stored locally somewhere.
另外,传递int或string要好得多,因为Drawables
的大小通常会很大,这可能会导致您的应用程序崩溃,原因是超出了意图的大小.
Also, passing int or string is much better, because Drawables
tend to be large is size, which might cause your app to crash due to size exceeded for an intent extras.
这是一篇文章,您也可以阅读该文章.
Here's an article where you can read about that as well.
这篇关于在Activity和Fragment之间传递对象时,是否发生序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!