How to show text on image

I have written code in which I display images in a GridView, but now I want to show the text at the bottom of each image.

And I want to show my grid as follows:

enter image description here

but it turns out like [I also want to show the text for the image]:

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> 
+7
source share
1 answer

You need to define a custom layout for the grid item that contains the text view for assigning 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> 

Here we created a FrameLayout, in which the figurative image is set in accordance with the parental dimensions, this will be the image that displays the photo. Next, there is a TextView that will be used to display the title of the element and is aligned at the bottom of the FrameLayout.

Then we need to edit your adapter to use this grid element layout and display 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 must be globally defined in your constructor using

 mLayoutInflater = LayoutInflater.from(context); 
+7
source

All Articles