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