Android L Elevation Effect in Pre L (only using elevation property)

一笑奈何 提交于 2019-12-03 22:47:05

If you want to set views in 3D shape, View.setElevation() and View.setTranslationZ() is a good idea.

But unfortunately, the two attributes and methods are introduced since Android API 21. So, you can't use them on pre-L or API 21- devices.

But, there is still a way to custom your views' shadows and outlines.

The bounds of a view's background drawable determine the default shape of its shadow. Outlines represent the outer shape of a graphics object and define the ripple area for touch feedback.

Consider this view, defined with a background drawable:

<TextView
android:id="@+id/myview"
...
android:elevation="2dp"
android:background="@drawable/myrect" />

The background drawable is defined as a rectangle with rounded corners:

<!-- res/drawable/myrect.xml -->
<shape xmlns:android="http://schemas.android.com/apk/res/android"
       android:shape="rectangle">
    <solid android:color="#42000000" />
    <corners android:radius="5dp" />
</shape>

The view casts a shadow with rounded corners, since the background drawable defines the view's outline. Providing a custom outline overrides the default shape of a view's shadow.

To define a custom outline for a view in your code:

  1. Extend the ViewOutlineProvider class.
  2. Override the getOutline() method.
  3. Assign the new outline provider to your view with the View.setOutlineProvider() method.

You can create oval and rectangular outlines with rounded corners using the methods in the Outline class. The default outline provider for views obtains the outline from the view's background. To prevent a view from casting a shadow, set its outline provider to null.

Hopefully it helps.

P.S.: yourAppNs:elevation="4dp" will be a good idea if you are using android-design-library.

EE66
  • ViewCompat.setElevation()/getElevation() doesnt work on pre Lollipop.
  • There isnt anything worth checking out at the support library, at least until version 21.1.1
  • As for creating an elevation effect by yourself take a look at this
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!