0

我需要在每张图片下显示图片描述,但出现无法转换的GridView错误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;
    }
4

1 回答 1

1

convertView 将成为您的父视图,在这种情况下是 GridView。这就是为什么您收到无法转换错误的原因。您正在尝试将其转换为 ImageView (以及 TextView )。

您应该将 ImageView 和 TextView 放在一个 cell.xml 布局文件中。然后在 getView() 调用期间膨胀并填充该 xml 文件,而不是为网格中的每个单元格创建新的 TextView / ImageView 实例。

这是涵盖这些主题的教程。他甚至使用了您的具体示例(每个单元格中的文本和图像)。完成本教程后,您只需稍作修改,以使文本位于图像下方,如果这是您希望它出现的方式。

于 2012-06-12T17:44:21.270 回答