2012-06-12 26 views
0

我需要顯示的每個圖像下的圖片說明,但我得到一個錯誤,我不能投GridViewTextView如何在網格佈局中的每個圖像下添加TextView?

XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 
    <GridView 
     android:id="@+id/main_gridview" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:numColumns="2" 
     android:padding="10dp" 
     android:verticalSpacing="30dp" /> 

    <TextView 
     android:id="@+id/tvIconDesc" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:textSize="15sp" /> 
</LinearLayout> 

代碼:

public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView imageView; 
     TextView textView; 
     if (convertView == null) { 
      textView = new TextView(mContext); 
      imageView = new ImageView(mContext); 
      imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE); 
      //imageView.setLayoutParams(new GridView.LayoutParams(100, 100)); 
     } else { 
      imageView = (ImageView) convertView; 
      textView = (TextView) convertView; 
     } 

     imageView.setImageResource(mThumbIds[position]); 
     textView.setText(thumbDesc[position]); 
     return imageView; 
    } 

回答

1

convertView將成爲你的父視圖,在這種情況下是一個GridView。這就是爲什麼你得到了無法轉換錯誤。你正試圖把它轉換成ImageView(和TextView)。

您應該將ImageView和TextView放在cell.xml佈局文件中。然後在getView()調用期間膨脹並填充該xml文件,而不是爲網格中的每個單元創建TextView/ImageView的新實例。

Here is a tutorial涵蓋了這些主題。他甚至使用了您的具體示例(每個單元格中的文本和圖像)。一旦你完成了本教程,你只需要稍微修改它就可以讓文本進入圖像下方,如果這是你希望它出現的方式。

相關問題