Search code examples
androidandroid-layoutandroid-imageviewtextview

Add TextView over ImageView (Android)


i am displaying full screen image in ImageView and i am trying to add TextView in center of screen over ImageView but TextView is not showing.

i tried:

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

    <ImageView
        android:id="@+id/splash_imageview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="centerCrop" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:layout_marginBottom="20dip"
        android:background="#AA000000"
        android:padding="12dip"
        android:text="SomeText"
        android:textColor="#ffffffff" />

</LinearLayout>

Solution

  • You may use FrameLayout, AbsoluteLayout (deprecated) or RelativeLayout (most common of these). An example of RelativeLayout, for centering is used android:layout_centerInParent="true", set for both childs

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
        <ImageView
            android:id="@+id/splash_imageview"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_centerInParent="true"
            android:scaleType="centerCrop" />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="20dip"
            android:layout_centerInParent="true"
            android:background="#AA000000"
            android:padding="12dip"
            android:text="SomeText"
            android:textColor="#ffffffff" />
    
    </RelativeLayout>
    

    Drawing Views is in the same order as in XML, so ImageView will be drawn first and then TextView over it

    Another approach would be to use FrameLayout with android:gravity="center" attr (nothing needed for childs)

    Also remeber and read about android:elevation and android:translationZ XML attributes, which may reorder drawing, and also view.bringToFront() method