Android "Elevation" does not show shadow under CustomView

I have a CustomView that works with pre-Lollipop, now I tried applying android:elevation and android:translateZ on Lollipop devices, but it doesn't seem to work.

 <com.example.CustomView android:id="@+id/myview" android:layout_width="wrap_content" android:layout_height="wrap_content" android:elevation="10dp"> </com.example.CustomView> 

What am I missing?

+6
source share
1 answer

As indicated in Defining Shadows and Cropping Views

You must implement the ViewOutlineProvider abstract class with which the View creates the Outline used for shadow casting and trimming.

Rectangular CustomView

 public class CustomView extends View { // .. @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { /// .. if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { setOutlineProvider(new CustomOutline(w, h)); } } @TargetApi(Build.VERSION_CODES.LOLLIPOP) private class CustomOutline extends ViewOutlineProvider { int width; int height; CustomOutline(int width, int height) { this.width = width; this.height = height; } @Override public void getOutline(View view, Outline outline) { outline.setRect(0, 0, width, height); } } //... } 

Note. This function is only supported by API21, pre API21 should use 9-patch.

+15
source

Source: https://habr.com/ru/post/979677/


All Articles