如何在图片上显示文字

7
我写了一段代码,在GridView中显示图片,但现在我想在每张图片的底部显示文本。
我想要显示的GridView如下图所示: enter image description here 但我得到的结果是这样的[也想为图片显示文本]: enter image description here main.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <GridView
        android:id="@+id/gridview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:verticalSpacing="0dp"
        android:horizontalSpacing="0dp"
        android:stretchMode="columnWidth"
        android:numColumns="2" 
        />
</FrameLayout>

这里的问题是什么? - Ovidiu Latcu
2
为您的GridView的项创建自定义布局,将图像和TextView放置在其中,并在适配器中填充它们。 - hardartcore
同意 @Android-Developer - Chetan
可能是重复的 https://dev59.com/4GUp5IYBdhLWcg3wdXaa - Georgy Gobozov
1个回答

7
您需要定义一个自定义网格项布局,其中包含一个文本视图来分配文本。
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >
    <ImageView
        android:id="@+id/thumbnail"
        android:padding="8dp"
        android:scaleType="cropCenter"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:layout_gravity="bottom"
        android:textColor="@android:color/white"
        android:background="#55000000" />
</FrameLayout>

这里我们创建了一个FrameLayout,其中imageView被设置为与父容器的尺寸匹配,这将是显示照片的imageView。接下来是一个TextView,用于显示项目标题,并对齐到FrameLayout的底部。
接下来,我们需要编辑适配器以使用此网格项布局并呈现正确的信息。
public View getView(int position, View convertView, ViewGroup parent) {

    // Inflate the single grid item layout
    if (convertView == null) {  
        convertView = mLayoutInflater.inflate(R.layout.grid_item, parent, false);
    }

    // Set Image
    ImageView thumbnail = convertView.findViewById(R.id.thumbnail);
    if (thumbnail != null) {
        thumbnail.setImageResource(mThumbIds[position]);
    }

    // Set Text
    TextView title = convertView.findViewById(R.id.title);
    if (title != null) {
        title.setText("Image Number: " + position);
    }

    return convertView;     
}

在构造函数中全局定义mLayoutInflater,使用以下代码:

mLayoutInflater = LayoutInflater.from(context);

这将是实现您想要的功能最有效的方法,因为使用自定义适配器可以回收视图并自定义内容。 - kandroidj

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接