从适配器内部处理多个 getView 调用的最佳方法 [英] Best way to handle multiple getView calls from inside an Adapter
问题描述
我有一个带有自定义 ArrayAdapter
的 ListView
.此 ListView
中的每一行都有一个图标和一些文本.这些图标在后台下载,缓存,然后使用回调,在各自的ImageViews
中替换.每次 getView
() 运行时都会触发从缓存或下载中获取缩略图的逻辑.
I have a ListView
with custom ArrayAdapter
. Each of the row in this ListView
has an icon and some text. These icons are downloaded in background,cached and then using a callback, substituted in their respective ImageViews
. The logic to get a thumbnail from cache or download is triggered every time getView
() runs.
现在,根据罗曼盖伊的说法:
Now, according to Romain Guy:
绝对不能保证getView() 的顺序叫了多少次."
"there is absolutely no guarantee on the order in which getView() will be called nor how many times."
我见过这种情况,因为一行大小为 2 的 getView() 被调用了六次!
I have seen this happen, for a row of size two getView() was being called six times!
如何更改我的代码以避免重复的缩略图提取请求并处理视图回收?
How do I change my code to avoid duplicate thumbnail-fetch-requests and also handle view recycling?
谢谢.
推荐答案
来自 api.
public abstract View getView (int position, View convertView,
ViewGroup parent)
convertView - 如果可能,要重用的旧视图.注意:在使用之前,您应该检查此视图是否为非空且类型合适.如果无法转换此视图以显示正确的数据,则此方法可以创建一个新视图.
convertView - The old view to reuse, if possible. Note: You should check that this view is non-null and of an appropriate type before using. If it is not possible to convert this view to display the correct data, this method can create a new view.
因此,如果已经为此特定索引调用了 getView,则 convertView 将是从第一次调用返回的 View 对象.
So if getView has already been called for this specific index then convertView will be the View object that was returned from that first call.
你可以做类似的事情.
if(!(convertView instanceof ImageView)){
convertView = new ImageView();
//get image from whereever
} else {} // ImageView already created
这篇关于从适配器内部处理多个 getView 调用的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!