gpt4 book ai didi

android - 何时以及为什么 ViewHolder 应该在 baseadapter 中使用

转载 作者:太空宇宙 更新时间:2023-11-03 13:16:43 25 4
gpt4 key购买 nike

ViewHolder 应该在什么时候使用?我在 ListViewGridView 的大部分代码中发现了这一点。如果有人能解释一下。谢谢。

最佳答案

ViewHolder 模式有什么用?

ViewHolder 设计模式使您无需查找即可访问每个列表项 View ,从而节省宝贵的处理器周期。具体来说,它避免了在ListView滚动过程中频繁调用findViewById(),这样会更流畅。

没有 ViewHolder 设计模式

让我们来看看我们之前在 ArrayAdapterItem.java 中的 getView() 方法

  1. 第一次加载时,convertView 为空。我们必须扩充我们的列表项布局并​​通过 findViewById() 找到 TextView。

  2. 第二次加载,convertView不为null,good!我们不必再次给它充气。但我们将再次使用 findViewById()。

  3. 以后加载的时候,convertView肯定不为null。但是 findViewById() 会不断被调用,它会起作用,但是会降低性能,尤其是当您的 ListView 中有很多项目和 View 时。

使用 ViewHolder 设计模式

现在让我们看看它是如何与 ViewHolder 模式一起工作的。

  1. 第一次加载时,convertView 为空。我们必须膨胀我们的列表项布局,实例化 ViewHolder,通过 findViewById() 找到 TextView 并将其分配给 ViewHolder,并将 ViewHolder 设置为 convertView 的标签。

  2. 第二次加载,convertView不为null,good!我们不必再次给它充气。好消息是,我们不必调用 findViewById(),因为我们现在可以通过 ViewHolder 访问 TextView。

  3. 下次加载时,convertView肯定不为null。 findViewById() 再也不会被调用,这使我们的 ListView 滚动流畅。

通过Android Adapter , 和 ViewHolder Pattern有关示例的更多详细信息。


官方 ,

为什么要使用 VIEWHOLDER?

因为,在 View 持有者中持有 View 对象

Your code might call findViewById() frequently during the scrolling of ListView, which can slow down performance. Even when the Adapter returns an inflated view for recycling, you still need to look up the elements and update them. A way around repeated use of findViewById() is to use the "view holder" design pattern.

A ViewHolder object stores each of the component views inside the tag field of the Layout, so you can immediately access them without the need to look them up repeatedly. First, you need to create a class to hold your exact set of views.

例如:

static class ViewHolder {
TextView text;
TextView timestamp;
ImageView icon;
ProgressBar progress;
int position;
}

然后填充 ViewHolder 并将其存储在布局中。

ViewHolder holder = new ViewHolder();
holder.icon = (ImageView) convertView.findViewById(R.id.listitem_image);
holder.text = (TextView) convertView.findViewById(R.id.listitem_text);
holder.timestamp = (TextView) convertView.findViewById(R.id.listitem_timestamp);
holder.progress = (ProgressBar) convertView.findViewById(R.id.progress_spinner);
convertView.setTag(holder);

现在您无需查找即可轻松访问每个 View ,从而节省宝贵的处理器周期。

关于android - 何时以及为什么 ViewHolder 应该在 baseadapter 中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34939432/

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