2015-09-04 49 views
-2

我明白了,因爲我的list_item.xml但什麼是畢加索錯誤android.widget.RelativeLayout不能轉換到android.widget.ImageView

我收到此錯誤

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"/> 

但爲什麼呢?如何使它與相關佈局工作

回答

3

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)); 
+0

哦,我沒有注意到這一點,我這樣離開正確的充氣? convertView = inflater.inflate(R.layout.list_item,parent,false); – Moudiz

+0

是的,你可以離開充氣器。 –

相關問題