androidxmlandroid-layoutandroid-viewview-hierarchy

android:layout_alignTop does not work similar to android:layout_alignBottom


I try to create a semi-transparent red View and a TextView inside RelativeLayout, which the height of View follows the height of TextView, it works as expected when the TextView is above the semi-transparent red View:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
    android:background="#FF0000"
    android:alpha="0.5"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@id/textView"/>
<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TEST"
    android:textSize="50dp"
    android:textColor="#000000"/>
</RelativeLayout>

enter image description here

but I want to change it a bit: put the View above the TextView and others remain unchanged, I tried change android:layout_alignBottom into android:layout_alignTop:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<View
    android:background="#FF0000"
    android:alpha="0.5"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignTop="@id/textView"/>
<TextView
    android:id="@+id/textView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TEST"
    android:textSize="50dp"
    android:textColor="#000000"/>
</RelativeLayout>

but now the View seems doesn't follow the height of TextView:

enter image description here

What is the problem and how can I fix it?


Solution

  • Add android:layout_alignBottom="@+id/textView" in View. e.g.-

    <View
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignTop="@id/textView"
            android:layout_alignBottom="@+id/textView"
            android:alpha="0.5"
            android:background="#FF0000" />