gpt4 book ai didi

android - 在 Android 中使用自定义适配器和 SoftReference 时的性能建议

转载 作者:行者123 更新时间:2023-11-29 14:54:08 27 4
gpt4 key购买 nike

我实现了一个自定义适配器来创建一个显示与位置相关的信息的对话框(对话框的每个条目都包含一个图像、一个显示地址的文本字段和一个显示城市和国家/地区的文本字段。)在适配器的 getView (...) 方法 除了使用 ViewHolder 模式外,我还使用 SoftReference 类来保存对创建的 View 的引用,以便 GC 可以在发生 OutOfMemoryError 之前消除其中的任何一个。我的目标是构建一个更快、更高效的缓存。在我的自定义适配器的代码下方:

public class LocationsAdapter extends ArrayAdapter<LocationInfo> {

Context context;
int layourResourceId;
List<LocationInfo> locations;

public LocationsAdapter(Context context, int layourResourceId,
List<LocationInfo> locations) {
super(context, layourResourceId, locations);

this.context = context;
this.layourResourceId = layourResourceId;
this.locations = locations;
}

@Override
public View getView(int position, View row, ViewGroup parent) {

LocationItemHolder holder = null;

if (row != null && ((SoftReference<LocationItemHolder>) row.getTag()).get() != null) {

holder = (LocationItemHolder) ((SoftReference<LocationItemHolder>) row.getTag()).get();

} else {

LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layourResourceId, parent, false);

holder = new LocationItemHolder();
holder.imgMarker = (ImageView) row.findViewById(R.id.imgMarker);
holder.txtNameStreet = (TextView) row
.findViewById(R.id.txtNameStreet);
holder.txtRegion = (TextView) row.findViewById(R.id.txtRegion);

row.setTag(new SoftReference<LocationItemHolder>(holder));
}

LocationInfo location = locations.get(position);
holder.imgMarker.setImageResource(location.getMarkerId());
holder.txtNameStreet.setText(location.getNameStreet());
holder.txtRegion.setText(location.getRegion());

return row;
}

class LocationItemHolder {
ImageView imgMarker;
TextView txtNameStreet;
TextView txtRegion;
}
}

我对让事情尽可能高效非常感兴趣。尽管代码满足了我的要求,但我不确定我是否很好地使用了 SoftReference 类。例如句子 (LocationItemHolder) ((SoftReference ) row.getTag ()).get() 我认为这会使缓存无效,因为每次调用检索所需对象的方法数量调用方法 getView 时,也需要多次转换。那句话会使缓存效率低下吗?。在 Android 的适配器上下文中使用 SoftReference 是否可取?

预先感谢您的回答:D

最佳答案

据我所知,在这里使用 SoftReference 没有意义。如果您正确地回收了 View (看起来确实如此),您将只有几个 LocationItemHolder 实例,它们总是相同的(在同一个适配器中)。它们唯一会失效的时间是适配器停止使用时。

关于android - 在 Android 中使用自定义适配器和 SoftReference 时的性能建议,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10405455/

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