我正在用多个项目填充GridView,每个项目都包含 ImageView 和 TextView,大约有 100 多个这样的项目。问题是一切都正常执行,但滚动时活动严重滞后,我试图通过限制图像大小来有效加载位图,但没有任何改进。
还要注意我的图像来源是本地文件系统,Category.getCategoryUrl() 包含文件路径。
这是我的ArrayAdapter实现:
public class RootCategoryAdapter extends ArrayAdapter<Category> {
private int resource;
private Context context;
private ArrayList<Category> categoryList;
private DisplayMetrics metrics;
public RootCategoryAdapter(Context context, int resource,
ArrayList<Category> categoryList, DisplayMetrics metrics) {
super(context, resource, categoryList);
// TODO Auto-generated constructor stub
this.context = context;
this.resource = resource;
this.categoryList = categoryList;
this.metrics = metrics;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
CategoryHolder holder = null;
if (convertView == null) {
// LayoutInflater inflater =(LayoutInflater)
// context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(resource, parent, false);
holder = new CategoryHolder();
holder.title = (TextView) convertView
.findViewById(R.id.root_category_text);
holder.image = (ImageView) convertView
.findViewById(R.id.root_category_image);
convertView.setTag(holder);
} else {
holder = (CategoryHolder) convertView.getTag();
}
Category category = categoryList.get(position);
holder.title.setText(category.getCategoryName());
// I think problem starts here but not certain
holder.options = new BitmapFactory.Options();
holder.options.inJustDecodeBounds = true;
holder.bitmap = BitmapFactory.decodeFile(category.getCategoryUrl(),
holder.options);
holder.options.inJustDecodeBounds = false;
holder.options.inSampleSize = BasicChores.calculateInSampleSize(
holder.options, 200, 200);
holder.bitmap = BitmapFactory.decodeFile(category.getCategoryUrl(),
holder.options);
holder.image.setImageBitmap(holder.bitmap);
return convertView;
}
static class CategoryHolder {
Bitmap bitmap;
BitmapFactory.Options options;
TextView title;
ImageView image;
}
@Override
public boolean hasStableIds() {
// TODO Auto-generated method stub
return true;
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return categoryList.get(position).getCategoryId();
}
@Override
public Category getItem(int position) {
// TODO Auto-generated method stub
return categoryList.get(position);
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return categoryList.size();
}
@Override
public int getPosition(Category item) {
// TODO Auto-generated method stub
return categoryList.indexOf(item);
}
}