gpt4 book ai didi

android - 使用 ViewHolder 模式时调用 Dispose() 的正确时机是什么时候?

转载 作者:行者123 更新时间:2023-11-30 00:53:04 24 4
gpt4 key购买 nike

我使用 James Montemagno 描述的 ViewHolder 模式

https://blog.xamarin.com/creating-highly-performant-smooth-scrolling-android-listviews/

考虑到FindViewById调用的对象,应该什么时候调用dispose呢?做什么是安全和正确的。我应该在某个时刻这样做: https://developer.xamarin.com/guides/android/advanced_topics/garbage_collection/

To shorten object lifetime, Java.Lang.Object.Dispose() should be invoked. TThis will manually "sever" the connection on the object between the two VMs by freeing the global reference, thus allowing the objects to be collected faster.

最佳答案

ListView 很旧(Android 1.0)。它是紧密耦合的,并没有考虑到性能。需要大量的技巧来保持它的相关性。 RecyclerView 填补了这个空白。

https://www.youtube.com/watch?v=LqBlYJTfLP4

至于何时应调用 Dispose()RecyclerView 应通过 LayoutManager 处理此基本功能。在 ViewHolder 端,您可以遵循基本的 Dispose 模式:

protected override void Dispose (bool disposing)
{
base.Dispose (disposing);
if(ItemView != null)
{
ItemView.Click -= HandleClick;
}
_listener = null; //Listener might just be a simple Action<int> like in this example: https://github.com/xamarin/monodroid-samples/blob/master/android5.0/RecyclerViewer/RecyclerViewer/MainActivity.cs#L111
}

在其中您只关心 Disposing 基础和您设置的任何事件处理程序。但是,如果您的 RecyclerViewView 中使用了一些图像,它正在膨胀,您需要确保正确管理这些资源,因为 Android GC 将无法收集这些资源项,因为它们将被 Xamarin.Android 的 GC 引用(并且它们将是一个像几个字节一样的小引用)。您必须以某种方式切断两个 GC 之间的链接,以便它有资格被收集。您可以在此处阅读有关 GC 算法的更多信息:Xamarin Android garbage collection algorithm原因在这里:https://developer.xamarin.com/guides/cross-platform/deployment,_testing,_and_metrics/memory_perf_best_practices/#Use_Weak_References_to_Prevent_Immortal_Objects

为此,我们可以通过几种方式切断关系:

  1. MyObject = null;
  2. MyObject.Dispose();

无论哪种方式都应将这些项目标记为符合 GC 条件。在 Drawable 的情况下,您可能还想将 Drawable 设置的相应 ImageView 或对象设​​置为 null 例如 SetBackgroundDrawable/etc.

TLDR;使用 RecyclerView,并记住适本地管理任何 Bitmap/Drawable 资源。

关于android - 使用 ViewHolder 模式时调用 Dispose() 的正确时机是什么时候?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40620486/

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