我有一个应用程序正在我的主屏幕上将sdcard中的图像加载到gridview。我创建了ViewHolder,因此视图只进行了一次实例化。在我使用smoothScrollToPosition
方法之前,这一切都运行良好。
当活动恢复或创建时,我会调用smoothScrollToPosition
,因此用户网格会立即滚动到所选位置。问题是它加载了网格开头的图像。
假设我有包含20个网格的GridView。只有2个具有图像,第一个和第二个,其他是空的(具有默认图像集)。现在在活动开始时我想顺利滚动到12位置。它应该是空的,但是12和13网格包含来自第一和第二网格的图像。如果已在此网格上加载图像,则不存在此问题。
我的适配器很典型:
public View getView(int position, View convertView, ViewGroup parent) {
dayNumber = dayList.get(position).getDayId();
imagePath = dayList.get(position).getPhotoPath();
if (convertView == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.gridview_cell, parent, false);
holder = new ViewHolder();
holder.day = (TextView) convertView.findViewById(R.id.dayDateTextView);
holder.image = (ImageView) convertView.findViewById(R.id.dayImage);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
setDayNumber(dayNumber);
setCurrentDay();
setBitmap(imagePath, parent, position);
return convertView;
}
我会感谢任何帮助。感谢
编辑:
适配器的其余部分:
private void setBitmap(String imagePath, ViewGroup parent, int position) {
if (imagePath != null) {
setBitmapFromSd(parent, position);
} else {
holder.image.setImageResource(R.drawable.ic_action_camera);
}
}
private void setBitmapFromSd(ViewGroup parent, int position) {
Bitmap bitmap = getBitmapFromMemCache(imagePath);
if (bitmap != null) {
holder.image.setImageBitmap(bitmap);
} else {
BitmapWorkerTask task = new BitmapWorkerTask(holder.image, parent, this, dayList.get(position));
task.execute(imagePath);
}
}
这是BitmapWorkerTask:
public BitmapWorkerTask(ImageView imageView, ViewGroup parent, PhotoAdapter photoAdapter, Day day) {
imageViewReference = new WeakReference<ImageView>(imageView);
this.photoAdapter= photoAdapter;
this.parent = parent;
this.day = day;
}
protected Bitmap doInBackground(String... path) {
Bitmap bitmap = null;
try {
bitmap = PhotoUtils.decodeSampledBitmapFromFile(parent, path[0]);
photoAdapter.addBitmapToMemoryCache(path[0], bitmap);
} catch (Exception e) {
dbAdapter.setDayImage(null, day.getDayId(), day.getMonthId(), day.getYearId());
}
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
if (imageViewReference != null && bitmap != null) {
final ImageView imageView = imageViewReference.get();
if (imageView != null) {
imageView.setImageBitmap(bitmap);
}
}
}
答案 0 :(得分:1)
我建议你做这样的事情:
getView
方法中你是&holder; .mage.setTag(imagePath);`BitmapWorkerTask
并将其命名为imagePath
this.imagePath = path[0];
doInBackground
在onPostExecute
方法中添加以下行:
if (imageView != null) {
String imagePath = (String)imageView.getTag();
if (imagePath.equals(this.imagePath) {
imageView.setImageBitmap(bitmap);
}
}
我希望这可以解决您的问题