Search code examples
androidandroid-layoutmaterial-designandroid-elevation

What's wrong with this layout that's causing the elevation shadow not to appear?


I'm trying to use Android Elevation to achieve the 'shadow' look for a view. The following is the layout xml:

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.sample.app.Main2Activity">

    <LinearLayout
        android:layout_width="395dp"
        android:layout_height="match_parent"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:orientation="vertical"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:clipChildren="false">

        <TextView
            android:id="@+id/textView2"
            android:layout_width="match_parent"
            android:layout_height="165dp"
            android:background="#FFFFFF"
            android:padding="30dp"
            android:layout_margin="30dp"
            android:elevation="10dp"
            android:text="TextView" />
    </LinearLayout>
</android.support.constraint.ConstraintLayout>

This is how the layout looks: Look ma, no shadows!

Any suggestions to fix this?


Solution

  • I'll get to the answer, but some background first. I was trying to achieve the look with a custom view that used a ConstraintLayout. This view would be used in another layout. I was when I tried using a simple TextView that I realised that the shadows weren't being rendered because, thus destroying my assumption that it was something ConstraintLayout related.

    What worked? I know, from the documentations, that shadows and rendered using a View's background. This, I have, and indeed, it was a solid color with no alpha value (as others on SO have mentioned). Much like so:

        <?xml version="1.0" encoding="utf-8"?>
        <shape xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">
            <solid android:color="#ffffff" />
        </shape>
    

    It was after I added android:radius to this, and then the shadows were rendered.

    <?xml version="1.0" encoding="utf-8"?>
    <shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <solid android:color="#ffffff" />
        <corners android:radius="1dp" />
    </shape>
    

    And if you were wondering, why not set it to 0dp? Well, the shadows disappear again when the radius values were set to 0dp.