我在我的应用程序中有一个Gridview,但问题是它再次加载所有图像,因为我滚动导致严重滞后,我怎样才能让它一次加载所有图像并缓存它?
package com.example.helloworld;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Constructor
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// Keep all Images in array
public Integer[] mThumbIds = {
R.drawable.sample_0,
R.drawable.sample_1,
R.drawable.sample_2,
R.drawable.sample_3,
R.drawable.sample_4,
R.drawable.sample_5,
R.drawable.sample_6,
R.drawable.sample_7,
R.drawable.sample_8,
R.drawable.sample_9,
R.drawable.sample_10,
R.drawable.sample_11,
R.drawable.sample_12,
R.drawable.sample_13,
R.drawable.sample_14,
R.drawable.sample_15,
R.drawable.sample_16,
R.drawable.sample_17
};
}
答案 0 :(得分:0)
如果你查看方法setImageResource的文档,它说它可能会导致用户界面缓慢。该文档提供了另一种选择:使用setImageDrawable。第二件事是,似乎ImageAdapter每次滚动GridView时都会为ImageViews调用setImageResource方法,而不是在生成GridView时调用一次。您可以通过增加图像数组的范围来解决这个问题。在这种情况下,这很有效,因为GridView始终具有与mThumbIds数组定义的元素数相同的元素。
示例:
要让所有图像只生成一次,将Drawable数组添加到类中,并在构造期间填充它:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
// Added drawable array:
private Drawable[] mDrawables;
public ImageAdapter(Context c) {
mContext = c;
// Fill in drawables with the images:
for (int i = 0; i < mThumbIds.length; i++) {
Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), mThumbIds[i]);
mDrawables[i] = new BitmapDrawable(mContext.getResources(), bitmap);
}
} `
现在,您所要做的就是更改setImageDrawable的setImageResource并传递mDrawables数组的成员:
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
// Changed to setImageDrawable:
imageView.setImageDrawable(mDrawables[pposition]);
return imageView;
}
结果是图像只会加载到Drawables中并存储一次,而setImageDrawable可以更快地访问这些图像,从而修复滚动。