How to implement a simple gradient shadow anchored by a Toolbar which lives in a CoordinatorLayout and could be collapsing as well? Something like that:
First of all here are a shadow drawable itself (named drawable/toolbar_dropshadow.xml):
<?xml version="1.0" encoding="utf-8"?> <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle"> <gradient android:startColor="@android:color/transparent" android:endColor="#88333333" android:angle="90"/> </shape>
Second, shadow should be tied to the Toolbar. Like that:
<?xml version="1.0" encoding="utf-8"?> <android.support.design.widget.CoordinatorLayout 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="match_parent" android:fitsSystemWindows="true"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <android.support.design.widget.CollapsingToolbarLayout android:id="@+id/collapsing_toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_scrollFlags="scroll|exitUntilCollapsed" app:contentScrim="?attr/colorPrimary" app:expandedTitleMarginStart="72dp" app:expandedTitleMarginEnd="64dp"> <!-- content --> </android.support.design.widget.CollapsingToolbarLayout> </android.support.design.widget.AppBarLayout> <android.support.v4.widget.NestedScrollView android:layout_width="match_parent" android:layout_height="match_parent" android:clipChildren="false" android:clipToPadding="false" android:layout_gravity="fill_vertical" app:layout_behavior="@string/appbar_scrolling_view_behavior"> <!-- content --> </android.support.v4.widget.NestedScrollView> <RelativeLayout android:layout_width="match_parent" android:layout_height="10dp" app:layout_anchor="@id/collapsing_toolbar" app:layout_anchorGravity="bottom"> <View android:layout_width="match_parent" android:layout_height="5dp" android:layout_alignParentBottom="true" android:background="@drawable/toolbar_dropshadow"/> </RelativeLayout> </android.support.design.widget.CoordinatorLayout>
Note that when using app:layout_anchor attribute in some view the latter is laid out in the way such that view’s center point is just aligned on the line specified by the app:layout_achorGravity attribute. This leads the shadow view (which is just a rectangle of 5dp height and matches the parent by width) to overlap with the toolbar. In order to avoid that one should place the shadow view into container which height is twice of shadow’s height and supply an anchor attribute to that container. Thus the shadow view will get a necessary margin (don’t forget to supply android:layout_alignParentBottom=”true” as well).