Search code examples
androidandroid-layoutandroid-imageviewtextviewandroid-xml

how to add text with highlight color background it to ImageView


I trying to add text with highlight color to ImageView, I doing some search and I found this answer and I applied it successfully, but I need to make background highlight of text with color black like this in image

destination

the current XML

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/postImage"
        android:layout_width="match_parent"
        android:layout_height="125dp"
        android:layout_margin="2dp"
        android:scaleType="centerCrop"
        android:src="@mipmap/ic_launcher" />

    <TextView
        android:id="@+id/postTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignStart="@id/postImage"
        android:layout_alignEnd="@id/postImage"
        android:layout_alignRight="@id/postImage"
        android:layout_alignLeft="@id/postImage"
        android:layout_alignTop="@+id/postImage"
        android:layout_alignBottom="@+id/postImage"
        android:layout_margin="1dp"
        android:ellipsize="end"
        android:gravity="center|bottom"
        android:maxLines="2"
        android:text="Hello"
        android:textColor="@color/white"
        android:textSize="14sp" />
</RelativeLayout>

Solution

  • Simple way is : Add background color to text view and set alpha value based on transparency.

        <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
    
        <ImageView
            android:id="@+id/image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/my_image"
            />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="lasdfjsdfjlsdkfj"
            android:background="@android:color/black"
            android:textColor="@android:color/white"
            android:layout_alignBottom="@id/image"
            android:layout_alignLeft="@id/image"
            android:textSize="18sp"
            android:layout_alignRight="@id/image"
            android:alpha="0.5"/>
    
    </RelativeLayout>