5

使用列表和地图数据演示开发应用程序。对于演示文稿之间的切换,应使用带有图像的自定义开关,如下所示:

在此处输入图像描述

如何创建这样的自定义 switchcompat?

4

1 回答 1

0

这是一个很好的例子:

原始答案

您可以定义用于背景的可绘制对象和切换器部分,如下所示:

<Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:thumb="@drawable/switch_thumb"
    android:track="@drawable/switch_bg" />

现在您需要创建一个选择器来定义切换器可绘制对象的不同状态。这里是来自 Android 来源的副本:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
    <item android:state_pressed="true"  android:drawable="@drawable/switch_thumb_pressed_holo_light" />
    <item android:state_checked="true"  android:drawable="@drawable/switch_thumb_activated_holo_light" />
    <item                               android:drawable="@drawable/switch_thumb_holo_light" />
</selector>

这定义了拇指可绘制对象,即在背景上移动的图像。滑块使用了四个 Ninepatch图像:

停用的版本(Android 正在使用的 xhdpi 版本) 停用的版本
按下的滑块: 按下的滑块
激活的滑块(开启状态): 激活的滑块
默认版本(关闭状态): 在此处输入图像描述

在以下选择器中定义了三种不同的背景状态:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
    <item android:state_focused="true"  android:drawable="@drawable/switch_bg_focused_holo_dark" />
    <item                               android:drawable="@drawable/switch_bg_holo_dark" />
</selector>

停用版本: 停用的版本
重点版本: 重点版
和默认版本: 默认版本

要拥有样式开关,只需创建这两个选择器,将它们设置为您的开关视图,然后将七个图像更改为您想要的样式。

于 2017-03-01T12:20:39.703 回答