CardView goes on top of FrameLayout, but declared first

Konstantin Berkov picture Konstantin Berkov · Jul 25, 2015 · Viewed 11.7k times · Source

I have simple FrameLayout with support CardView as first item, and TextView as second, so TextView must be on top of inflated view. This works on pre-Lolipop but on 21+ card takes toppest place in layout, why that's so and how to fix this? Same thing with RelativeLayout. Layout:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="200dp"
        android:layout_margin="20dp"
        app:cardBackgroundColor="#ff0000"
        app:cardUseCompatPadding="false"
        />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="i am top view!"
        android:gravity="center"
        android:layout_gravity="center"
        android:textSize="30sp"
        android:textAllCaps="true"
        android:textColor="#00ff00"
        android:background="#0000ff"
        />

</FrameLayout>

Answer

Ereza picture Ereza · Apr 5, 2016

In case someone gets here and the solution for setting elevation doesn't work for them (like in my case, where I needed to draw an image above the CardView and having a shadow on it was not acceptable), you can solve the issue by wrapping the CardView inside another FrameLayout. In the example provided, it would look something like this:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <!-- This is the added FrameLayout -->
    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v7.widget.CardView
            android:layout_width="match_parent"
            android:layout_height="200dp"
            android:layout_margin="20dp"
            app:cardBackgroundColor="#ff0000"
            app:cardUseCompatPadding="false"
            />

    </FrameLayout>

    <TextView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:text="i am top view!"
        android:gravity="center"
        android:layout_gravity="center"
        android:textSize="30sp"
        android:textAllCaps="true"
        android:textColor="#00ff00"
        android:background="#0000ff"
        />

</FrameLayout>