滚动gridview时点击OutOfMemoryError。
适配器代码:
package com.example.gridviewexample;
import android.content.*;
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;
private Integer arrayElement[] = {
R.drawable.rkt, R.drawable.images,R.drawable.sir,R.drawable.sir2,
R.drawable.sir3,R.drawable.sir4, R.drawable.images1,
R.drawable.images3, R.drawable.indeerx,
R.drawable.index,R.drawable.rkt2,R.drawable.rkt3,R.drawable.rkt4,R.drawable.rkt5,R.drawable.sir2,
R.drawable.sir3,
};
public ImageAdapter(Context c){
mContext = c;
}
@Override
public int getCount() {
return arrayElement.length;
}
@Override
public Integer getItem(int position) {
return arrayElement[position];
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(mContext);
imageView.setImageResource(arrayElement[position]);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(200,200));
return imageView;
}
}
任何建议都将不胜感激!
答案 0 :(得分:2)
尝试这样做:
public View getView(int position, View convertView, ViewGroup parent) {
View grid = convertView;
if (convertView == null) {
grid = inflater.inflate(R.layout.grid1, parent, false);
}
TextView item = (TextView) grid.findViewById(R.id.item_title);
item.setBackgroundResource(mThumbIds[position]);
return grid;
}
我使用TextView
来显示图片,您可以尝试自己将TextView
更改为ImageView
。
答案 1 :(得分:0)
它是known bug,这不是因为大文件。由于Android缓存Drawables,因此在使用少量图像后内存不足。但我通过跳过Android默认缓存系统找到了它的替代方式。
<强> Soultion 强>: 在Assets中创建一个drawable文件夹,并将图像移动到资源中的“drawable”文件夹,并使用以下函数获取BitmapDrawable
public static Drawable getAssetImage(Context context, String filename) throws IOException {
AssetManager assets = context.getResources().getAssets();
InputStream buffer = new BufferedInputStream((assets.open("drawable/" + filename + ".png")));
Bitmap bitmap = BitmapFactory.decodeStream(buffer);
return new BitmapDrawable(context.getResources(), bitmap);
}
答案 2 :(得分:0)
android:largeHeap="true"