正确实现 Custom Adapter 以使用 Picasso 显示图像

Properly implement Custom Adapter to show images with Picasso

我已经用不同的方式多次编写和重写这个适配器,但我唯一得到的是启动应用程序时的空白屏幕。

我想使用 picasso 和一串 url 作为基础数据将图像加载到 gridview 中,但我并没有真正进行下去。

https://github.com/Valakias/PortFolioMovieApp

问题是 imageView 宽度为 0(使用 Poster.getWidth(); 进行检查),这就是您看不到图像的原因,自定义适配器没问题。

您可以解决此问题,使用 setLayoutParams 将 width/height 设置为 imageView,如下例所示:

if (convertView == null) {
   LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
   convertView = inflater.inflate(R.layout.gridview_item, null);

   //Get screen size, and divide it by the number of columns of your grid view.
   int width = getContext().getResources().getDisplayMetrics().widthPixels / 2;
   ((ImageView) convertView.findViewById(R.id.gridview_item_image)).setLayoutParams(new GridView.LayoutParams(width, width));
}

ImageView Poster = (ImageView) convertView.findViewById(R.id.gridview_item_image);
Picasso.with(getContext())
       .load(getItem(position))
       .fit()
       .centerCrop()
       .into(Poster);

或使用 Picasso.resize

的不同方法
//Get screen size, and divide it by the number of columns of your grid view.
int width = getContext().getResources().getDisplayMetrics().widthPixels / 2;
ImageView Poster = (ImageView) convertView.findViewById(R.id.gridview_item_image);

Picasso.with(getContext())
    .load(getItem(position))     
    .resize(width, width)
    .centerCrop()
    .into(Poster);

您可以使用 .centerInside()

而不是 .centerCrop()
  • 使用 .centerCrop()

  • 使用 '.centerInside()'(这将尊重图像纵横比)。