如何在图像上显示文本 [英] How to show Text on Image
问题描述
我写了一个代码,我在 GridView 中显示图像,但现在我想在每个图像的底部显示文本.
I have written a code, in which i am showing images in GridView, but now i want to show text in bottom of every image.
我想像这样显示我的网格:
And i want to show my Grid like this:
但是像这样[也想显示图片文字]:
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>
推荐答案
您需要定义一个自定义的网格项布局,其中包含一个 textview 来分配文本.
You need to define a custom grid item layout which contains a textview to assign the text.
<?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 的底部对齐.
Here we have created a FrameLayout which has the imageview set to match the parent's dimensions, this will be the imageview that displays the photo. Next, there is a TextView which will be used to display the item title and that is aligned to the bottom of the FrameLayout.
接下来,我们需要编辑您的适配器以使用此网格项布局并呈现正确的信息.
Next, we need to edit your adapter to use this grid item layout and render the correct information.
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 should be globally defined in your constructor using
mLayoutInflater = LayoutInflater.from(context);
这篇关于如何在图像上显示文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!