2012-06-12 27 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涵盖了这些主题。他甚至使用了您的具体示例(每个单元格中的文本和图像)。一旦你完成了本教程,你只需要稍微修改它就可以让文本进入图像下方,如果这是你希望它出现的方式。

相关问题