更改所选开关轨道颜色

3
我有一个开关,当它被切换为开启状态时,我希望轨道的颜色是橙色,而当它被切换为关闭状态时,我希望轨道的颜色是灰色。然而,我不想破坏现有的thumb.xml和track.xml文件的大小设置。

custom_thumb.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="30dp"
        android:height="30dp" />
    <corners android:radius="15dp" />
    <solid android:color="@color/white" />
</shape>

custom_track.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="60dp"
        android:height="30dp" />
    <corners android:radius="15dp" />
    <solid android:color="@color/cold_grey06" />
</shape>

开关
<Switch
                android:id="@+id/rememberSwitch"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:thumb="@drawable/custom_thumb"
                android:track="@drawable/custom_track" />
1个回答

1
你可以在res/color文件夹中创建一个颜色资源,例如track_color.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="@color/orange"/>
    <item android:color="@color/cold_grey06"/>
</selector>

然后在custom_track.xml中使用它:
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <size
        android:width="60dp"
        android:height="30dp" />
    <corners android:radius="15dp" />
    <solid android:color="@color/track_color" />
</shape>

你只需创建一个资源,资源类型为Color,然后粘贴我的第一段代码,你可能只需要将orange替换为你的资源名称。 - undefined
是的,有的。轨道颜色。 - undefined
我在资源中没有颜色。 - undefined
你能给我的问题评个分吗? - undefined
完成了 :) 你能给我评个分吗? - undefined
显示剩余6条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接