毕加索错误 android.widget.RelativeLayout 无法转换为 android.widget.ImageView

picasso error android.widget.RelativeLayout cannot be cast to android.widget.ImageView

我理解是因为我的 list_item.xml 但这是什么原因

我遇到了这个错误

java.lang.ClassCastException: android.widget.RelativeLayout cannot be cast to android.widget.ImageView
E/AndroidRuntime(27089):    at com.example.jsn.ImageListAdapter.getView(ImageListAdapter.java:44)

这是我的代码

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        if (null == convertView) {
            convertView = inflater.inflate(R.layout.list_item, parent, false);
        }

        Picasso
            .with(context)
            .load(imageUrls[position])
            .placeholder(R.drawable.ic_launcher) // can also be a drawable
            .fit() // will explain later
            .noFade()
            .into((ImageView) convertView);  
        return convertView; // I guess here is my problem

    } 
}

这是我的xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#f0f0f0">

<ImageView 
    android:id="@+id/ImageView"
       android:layout_width="match_parent"
       android:layout_height="200dp"/>

</RelativeLayout>

当我像这样 list_item.xml 时它会起作用 :

<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/ImageView"
       android:layout_width="match_parent"
       android:layout_height="200dp"/>

但是为什么呢?如何让它与 relativelayout

一起工作

您的 convertViewinflater.inflate(R.layout.list_item, parent, false); 的结果,这意味着它是 list_item.xml 的根元素的实例,即 RelativeLayout.

要解决此问题,您需要执行以下操作:

    Picasso 
        .with(context) 
        .load(imageUrls[position])
        .placeholder(R.drawable.ic_launcher) // can also be a drawable
        .fit() // will explain later 
        .noFade() 
        .into((ImageView) convertView.findViewbyId(R.id.ImageView));