Search code examples
androidandroid-layoutimageviewandroid-imageviewandroid-xml

How to put text over ImageView


Currently I have a grid layout filled with images, but I want to display some text on them and the text will change/update over time. What would be the best option?

XML code looks something like this:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
<GridLayout
    android:id="@+id/GridLayout1"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="center"
    android:columnCount="3"
    android:rowCount="11"
    android:orientation="horizontal"
    tools:context=".MainActivity2" >

<Button
    android:id="@+id/my_button1"
    android:layout_height="wrap_content"
    android:layout_columnSpan="3"
    android:layout_gravity="center"
    android:layout_margin="5dp"
    android:layout_marginTop="700dp"
    android:layout_marginBottom="40dp"
    android:text="CLOSE CONNECTION" />

<ImageView
    android:id="@+id/my_img1"
    android:layout_width="120dp"
    android:layout_height="100dp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_svgimg_img"/>

<ImageView
    android:id="@+id/my_img2"
    android:layout_width="120dp"
    android:layout_height="100dp"
    android:layout_margin="5dp"
    android:src="@drawable/ic_svgimg_img"/>
.
.
.

Solution

  • For this purpose you can use a FrameLayout. Try something like this

    <FrameLayout>
      <ImageView />
      <TextView />
    </FrameLayout>
    

    The FrameLayout will overlap views, you can play with gravity to adjust positioning. If you need a more complex alignment you can go with more complex layouts like RelativeLayout or ConstraintLayout.