android - 如何设计 Android Switch?

标签 android android-theme styling android-styles android-switch

API 14 中引入的开关小部件默认采用全息主题样式。 我想把它的风格稍微改变一下,为了品牌的原因改变它的颜色和形状。怎么办?我知道这一定是可能的,因为我看到了默认 ICS 和三星的 touchwiz 主题之间的区别

enter image description here

我认为我需要一些状态可绘制对象,并且我在 http://developer.android.com/reference/android/R.styleable.html 中看到了一些样式Switch_thumb 和 Switch_track 看起来像我可能想要的。我只是不知道如何使用它们。

如果有什么不同,我正在使用 ActionbarSherlock。当然,只有运行 API v14 或更高版本的设备才能使用开关。

最佳答案

您可以定义用于背景的drawable,以及像这样的切换器部分:

<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用于 slider 的图像:

停用的版本(Android 正在使用的 xhdpi 版本)The deactivated version
按下的 slider :The pressed slider
激活的 slider (开启状态):The activated slider
默认版本(关闭状态):enter image description here

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

<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>

停用的版本:The deactivated version
重点版本:The focused version
默认版本:the default version

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

关于android - 如何设计 Android Switch?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10118050/

相关文章:

android - 在 Android 中检测蓝牙 Le 设备

java - 按下项目时 ListView 不触发

Android Actionbar 导航微调器文本颜色

xaml - 使用静态内容样式化列表框

java - Vaadin 组件样式困惑

android - 使用React Native在Android中使用bundle id打开其他应用程序?

c# - Xamarin Android 将数据从类传递到 Activity

android - 在 Android 上应用应用程序范围的自定义字体

Android setTheme() 不改变 ActionBar 和状态栏

html - 将 li 元素包含在导航栏中