Android“提升”未在CustomView下显示阴影

时间:2014-12-16 05:16:51

标签: android android-custom-view android-elevation

我有一个自定义视图在Lollipop之前工作,现在我尝试在Lollipop设备上应用android:elevationandroid:translateZ,但似乎不起作用。

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

我错过了什么?

1 个答案:

答案 0 :(得分:24)

正如Defining Shadows and Clipping Views

中所述

你应该实现ViewOutlineProvider抽象类,View构建它的Outline,用于阴影投射和剪辑

矩形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);
        }
    }

    //...
}

注意:此功能仅受API21支持,API21之前应使用9-patch。