How can I add a shadow to bottom sheet view?

Chris picture Chris · May 17, 2016 · Viewed 15k times · Source

As of now, with the official bottom sheet component from the Android design library implemented the top edge doesn't show a shadow. But for what I've seen in various mockups and in the Material Design specs, the bottom sheet include a discrete shadow of some sort.

I think the shadow would help distant the bottom sheet from the main layout, especially if there's a peek value set and/or the bottom sheet is always visible. Otherwise it just will blend together with the main layout and its items.

I've tried both ViewCompat.setElevation(bottomSheet, 5); and setting android:elevation="5dp" to the view in the XML, without success.

Bottom sheet example from Material Design specs

Answer

mbo picture mbo · Dec 2, 2016

I know that a shadow shape doesn't have the same appearance as an elevation - but at least give it a try. The trick is to use app:layout_anchor to clip the shadow to the bottom sheet.

activity_main.xml

<android.support.design.widget.CoordinatorLayout 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">

<MapView
    android:id="@+id/map"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

<View
    android:id="@+id/shadow"
    android:layout_width="match_parent"
    android:layout_height="16dp"
    android:background="@drawable/shape_gradient_top_shadow"
    app:layout_anchor="@id/bottom_sheet" />

<FrameLayout
    android:id="@+id/bottom_sheet"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:clipToPadding="false"
    app:layout_behavior="android.support.design.widget.BottomSheetBehavior" />

</android.support.design.widget.CoordinatorLayout>

shape_gradient_top_shadow.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
    android:angle="90"
    android:endColor="@android:color/transparent"
    android:startColor="#64000000"/>
</shape>

Looks like this:

Bottom Sheet Shadow

EDIT

Get an even better result with a custom ShadowView:

Then you can do the following:

<ShadowView
    android:id="@+id/shadow"
    android:layout_width="match_parent"
    android:layout_height="16dp"
    android:gravity="bottom"
    app:layout_anchor="@id/bottom_sheet" />