我正在尝试编写自己的自定义CursorAdapter
,它将在其旁边显示文本和图像。我正在使用视图持有者模式和AsyncTask
加载图像。我写的代码工作正常,加载一切都很好,直到我开始向下滚动列表,而不是加载到缩略图中的图像与上面行中出现的那些已经向上滚动的图像重复。我尝试了很多教程都不能在这里找到我做错了什么。帮助将不胜感激。
public class MyCustomCurserAdapter extends CursorAdapter {
private static class ViewHolder {
public TextView nameText;
public ImageView imageThumbnail;
public int position;
}
public MyCustomCurserAdapter(Context context, Cursor c, int flags) {
super(context, c, flags);
}
@Override
public void bindView(View view, Context arg1, Cursor cursor) {
ViewHolder holder = (ViewHolder)view.getTag();
int pathCol = cursor.getColumnIndex(NewPicSQLiteHelper.COLUMN_PATH);
String imageInSD = cursor.getString(pathCol);
File imgFile = new File(imageInSD);
if(imgFile.exists()){
int nameCol = cursor.getColumnIndex(NewPicSQLiteHelper.COLUMN_PIC_NAME);
String name = cursor.getString(nameCol);
if (name != null)
holder.nameText.setText(name);
ImageTask task = new ImageTask(holder,cursor.getPosition());
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imgFile.getAbsolutePath());
}
}
@Override
public View newView(Context arg0, Cursor cur, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.new_pic_item, parent, false);
ViewHolder holder;
holder = new ViewHolder();
holder.nameText = (TextView) view.findViewById(R.id.pic_name_entry);
holder.imageThumbnail = (ImageView) view.findViewById(R.id.pic_thumbnail);
holder.imageThumbnail.setTag(Integer.valueOf(cur.getString(NewPicSQLiteHelper.INDEX_COLUMN_ID)));
holder.position = cur.getPosition();
// The tag can be any Object, this just happens to be the ViewHolder
view.setTag(holder);
return view;
}
private class ImageTask extends AsyncTask<String, Void, Bitmap>{
private final WeakReference <ImageView> imageViewReference;
int viewID;
ViewHolder taskHolder;
public ImageTask(ViewHolder holder,int position) {
taskHolder = holder;
ImageView imageView = taskHolder.imageThumbnail;
imageViewReference = new WeakReference <ImageView> (imageView);
viewID = position;
}
@Override
protected Bitmap doInBackground(String... params) {
String path = params[0];
return decodeSampledBitmapFromResource(path,75,75);
}
@Override
protected void onPostExecute(Bitmap result) {
if (imageViewReference != null) {
ImageView imageView = imageViewReference.get();
if (imageView != null) {
Log.d("AsyncTask", "ImageView null");
if (result != null) {
if(viewID == taskHolder.position){
imageView.setImageBitmap(result);
imageView.setVisibility(ImageView.VISIBLE);
Log.d("AsyncTask", "Image position right");
}
} else {
Log.d("AsyncTask", "Image positions wrong");
imageView.setVisibility(ImageView.INVISIBLE);
}
}
}
}
private Bitmap decodeSampledBitmapFromResource(String orgImagePath, int reqWidth, int reqHeight) {
////.........
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
////.........
}