android:elevation only have shadow effects on the bottom side, how to make the shadow effects show on top side?

时光总嘲笑我的痴心妄想 提交于 2019-11-28 18:15:50

There is a trick that can be used to display a shadow above a View.

Basically we have to use two nested Layouts, where the outer Layout casts the shadow with an elevation and the inner layout sets the background. Then by setting a padding to the outer Layout, we can shift the inner Layout down, without moving the shadow, thus more of the shadow becomes visible:

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="50dp"
    android:elevation="4dp"
    android:outlineProvider="bounds"
    android:paddingTop="2dp"
    android:layout_marginTop="-2dp">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#00737f">

        <!-- content -->

    </FrameLayout>

</FrameLayout>

An important thing here is the attribute outlineProvider, that is required to make the outer Layout cast a shadow even without having a background set.

Further we specify a negative margin to compensate for the offset created by the padding. Depending on the use-case we can omit that.

But attention: If we shift the View too much, some rendering artifacts become visible:

Source of this example on Github

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!