我为我的图像制作了一个数组,以在 GridView list 中显示它们。问题是它占用了大量内存,滚动很慢(不流畅)并且每次都保持强制关闭。在我检查了解决方案后,我发现我需要将它们保存到存储中,然后在应用程序中使用它们。但它没有用。有人可以帮我怎么做吗?
这是我的适配器代码:
public class ImageAdapter extends BaseAdapter {
Context mContext;
// Keep all Images in array
public Integer[] mThumbIds = { R.drawable.d, R.drawable.t,
R.drawable.e, R.drawable.e, R.drawable.r,
R.drawable.asdt, R.drawable.asd, R.drawable.a,
//... etc
};
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and
// keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
int reqWidth, int reqHeight) {
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize=4;
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(res, resId, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeResource(res, resId, options);
}
// Constructor
public ImageAdapter(Context c) {
mContext = c;
}
@Override
public int getCount() {
return mThumbIds.length;
}
@Override
public Object getItem(int position) {
return mThumbIds[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
imageView = new ImageView(mContext);
imageView.setImageBitmap(decodeSampledBitmapFromResource(
imageView.getResources(), mThumbIds[position], 100, 100));
imageView.buildDrawingCache(isEmpty());
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
imageView.setLayoutParams(new GridView.LayoutParams(
(getScreenWidth() / 3), (getScreenWidth() / 3)));
return imageView;
}
@SuppressWarnings("deprecation")
@SuppressLint("NewApi")
public int getScreenWidth() {
int columnWidth;
WindowManager wm = (WindowManager) mContext
.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
final Point point = new Point();
try {
display.getSize(point);
} catch (java.lang.NoSuchMethodError ignore) { // Older device
point.x = display.getWidth();
point.y = display.getHeight();
}
columnWidth = point.x;
return columnWidth;
}
}