【问题标题】:How to keep a Switch thumb shadow/elevation when using a custom drawable for the thumb?为拇指使用自定义可绘制对象时如何保持切换拇指阴影/高度?
【发布时间】:2019-09-14 21:40:25
【问题描述】:

我需要用我自己的 drawable 替换默认的 Switch thumb。为此,我使用了 android:thumb 属性,它运行良好,但拇指下的阴影不再存在。如何在保持拇指阴影/高度的同时使用自定义拇指可绘制对象?

这是我实现的样式:

<style name="TiimeGreenSwitch" parent="Widget.AppCompat.CompoundButton.Switch">
    <item name="android:thumb">@drawable/switch_green_thumb</item>
    <item name="trackTint">@color/switch_green_track</item>
</style>

drawable 就是这个选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/switch_green_thumb_disabled" android:state_enabled="false" />
    <item android:drawable="@drawable/switch_green_thumb_checked" android:state_checked="true" />
    <item android:drawable="@drawable/switch_green_thumb_default" />
</selector>

每个drawable看起来像这样:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval">
    <size android:width="20dp" android:height="20dp" />
    <solid android:color="#ffffff" />
    <stroke android:width="1dp" android:color="@color/switch_checked" />
</shape>

编辑:按照 Gabe Sechan 的回答,我直接在 drawable 中实现了一个阴影,如下所示,它按预期工作:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

    <item>
        <shape android:shape="oval">
            <size
                android:width="22dp"
                android:height="22dp" />
            <solid android:color="#22000000" />
        </shape>
    </item>

    <item
        android:bottom="1dp"
        android:left="1dp"
        android:right="1dp"
        android:top="1dp">
        <shape android:shape="oval">
            <size
                android:width="20dp"
                android:height="20dp" />
            <solid android:color="#ffffff" />
            <stroke
                android:width="1dp"
                android:color="@color/switch_checked" />
        </shape>
    </item>

</layer-list>

【问题讨论】:

    标签: android user-interface shadow android-elevation


    【解决方案1】:

    将阴影放入drawable中。这就是它在默认可绘制对象中的工作方式,这就是您现在丢失它的原因。它确实是唯一的方法,因为操作系统不知道您实际使用的形状,并且最多只能在整个可绘制对象下方放置一个阴影,如果您使用圆形或圆形边缘,这将是错误的。

    【讨论】:

    • 完美运行,谢谢!我用您的答案的实施编辑了我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 2021-02-21
    相关资源
    最近更新 更多