【问题标题】:Android “elevation” is not showing a shadow under a CustomViewAndroid“海拔”没有在 CustomView 下显示阴影
【发布时间】:2015-02-14 08:55:42
【问题描述】:

我在 Lollipop 之前有一个 CustomView,现在我尝试在 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>

我错过了什么?

【问题讨论】:

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


    【解决方案1】:

    正如Defining Shadows and Clipping Views中提到的那样

    您应该实现ViewOutlineProvider 抽象类,View 通过该抽象类构建其Outline,用于阴影投射和剪辑

    矩形自定义视图

    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。

    【讨论】:

    • 我不太明白我们为什么要这样做。我这样做是因为这是我发现在自定义视图上显示阴影的唯一方法,但我不明白为什么。在编辑器预览中显示了我的自定义视图的阴影,只是设置了高度,但是当我运行它时它不显示阴影。我不想要自定义阴影只是自定义视图上的标准阴影。任何进一步的阅读或解释?
    • 我不确定为什么默认情况下不是边界框。负责生成环境/点阴影的框架代码使用 getOutline 来确定视图的形状。你的视图可能是正方形、圆形或六边形,没有其他方法可以知道。所以你必须提供一个大纲。
    • 如果您在自定义视图上使用自定义 Drawable,您也可以在您的 drawable 上实现 getOutline 而不是这种方法。
    • 只是为了澄清一下,通过“自定义 Drawable 您的自定义视图”,我说的是使用自定义 Drawable 子类作为视图的 背景
    • 我正在尝试使用它,但宽度和高度一直为零:(
    猜你喜欢
    • 2015-08-22
    • 2015-02-13
    • 2016-11-11
    • 1970-01-01
    • 2016-02-03
    • 2017-10-15
    • 2021-05-17
    • 2021-07-19
    • 1970-01-01
    相关资源
    最近更新 更多