网格视图滚动不流畅

Grid view scrolling is not smooth

我正在使用 GridView 显示图像,这些图像存储在设备的 SD 卡中。当我滚动 GridView 时,滚动不流畅。 customAdapter的getview函数如下:

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
   View view = inflater.inflate(R.layout.main_xml, parent, false);

   ImageView photo= (ImageView) view.findViewById(R.id.gImage);
   DisplayMetrics displaymetrics = new DisplayMetrics();
   getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
   int width = displaymetrics.widthPixels;
   photo.setLayoutParams(new LinearLayout.LayoutParams(width/2, width/2));

   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inSampleSize = 2;
   Bitmap bitmap = BitmapFactory.decodeFile(imageUrls.get(position).getimageUrl(), options);
   photo.setImageBitmap(bitmap);

   return view;
}

其中imageUrl为图片在Sd卡中位置的字符串arrayList。我还动态设置了 ImageView 的宽度和高度。

您正在主应用程序线程上以 decodeFile() 调用的形式执行磁盘 I/O。这会给你带来性能问题。

有很多图片加载库,比如Picasso and Universal Image Loader。请使用其中之一。他们会在后台加载您的图片,并在图片准备好后填充您的 ImageView。如果您坚持为此滚动自己的代码,请为您的磁盘使用 AsyncTask 或其他后台线程 I/O.

除此之外,正如 Selvin 在评论中指出的那样,请注意 convertViewgetView() 的参数,不要在不需要时盲目地膨胀布局。