gpt4 book ai didi

java - Android Parcelable 占用较多内存

转载 作者:搜寻专家 更新时间:2023-11-01 07:35:50 26 4
gpt4 key购买 nike

问题很简单,如果我使一个对象可打包,然后将其放入一个包中并使用该包创建一个 fragment 。对象是否被克隆或被引用。

上下文。

我在 ArrayList 中存储/引用了一个对象。取决于 ArrayList 中对象的类型(使用多态性)。我创建了一个适合处理它的 fragment 。

我还需要将此对象传递给 fragment 。该 fragment 在自定义 View 寻呼机中使用。我不希望有重复的对象,在我看来是可分割的克隆对象。

另一种方法是传递对象在ArrayList中的索引。然后使用 getActivity().myList.get(Integer passed to ) 从 fragment 中获取对数组列表的引用。但它对我来说似乎不太安全(ArrayList 内容可能会改变,尽管我只是删除所有内容并重新开始)。我还读到,您应该避免将参数传递给 fragment 构造函数,因为它可能会使用默认的无参数构造函数重新创建。

(虽然我目前正在销毁任何重新创建的 fragment ,因为重新附加到正确的 View 时存在一些奇怪的问题,另一篇文章)。

新的子问题:有没有办法通过对 fragment 的引用来传递值?

最佳答案

The question is simple, if I make an object parcelable, and put it into a bundle and create a fragment using the bundle. Does the object get cloned or is it referenced.

它可能会在其他时间点被克隆(如果不是立即)(例如,当 fragment 的参数 Bundle 包含在实例状态中时)。

I have also read, that you should avoid passing arguments to a fragments constructor as it may be recreated using the default no-args constructor.

正确。

Another method is to pass the index of the object in the ArrayList. and then get a reference to the arraylist from the fragment using getActivity().myList.get(Integer passed to ). But it doesnt seem very safe to me (ArrayList contents may change, although I simply delete everything and start again).

不要使用ArrayList。使用具有持久键的 HashMap。将 key 传递给 fragment 。让 fragment 通过键获取数据。确保任何删除此对象(并因此将其从 HashMap 中删除)的人仅在该 fragment 不存在时执行此操作,或通知此 fragment 以便它知道如何处理这种情况。

关于java - Android Parcelable 占用较多内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11474823/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com