5

我一直在尝试寻找资源来解释如何Switch在 Material Design 主题中设置按钮样式。

此链接确实解释了颜色值和美学细节,但并没有说明如何通过在材料设计主题中设置某些属性来实现这一点。

http://www.google.com/design/spec/components/switches.html#switches-switch

如果没有直接的方法来设置 Switch 的颜色,我可以用来制作自己的版本的可绘制对象在哪里?

4

3 回答 3

17

我一直在尝试寻找资源来解释如何在 Material Design 主题中设置切换按钮的样式。

现在使用新的 appcompat-v7:21 为小部件着色非常简单。

只要您使用的是 appcompat-v7:21,您就可以将所有旧Switch的小部件替换为小SwitchCompat部件。因此,在您的 xml 布局中,不要使用旧Switch标签,而是使用android.support.v7.widget.SwitchCompat.

然后在您的 styles.xml 中,确保您的应用程序的父主题是一个Theme.AppCompat主题,例如Theme.AppCompat.Light.

最后,关键是为 指定您自己的值colorAccent

<item name="colorAccent">@color/my_fancy_color</item>

您指定的颜色colorAccent将用于为您的应用程序中的小部件着色,例如SwitchCompatsEditTextsRadioButtons等。

所以你的 styles.xml 可能看起来像:

<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">
    <!-- colorPrimary is used for the default action bar background -->
    <item name="colorPrimary">@color/color_primary</item>

    <!-- colorPrimaryDark is used to color the status bar -->
    <item name="colorPrimaryDark">@color/color_primary_dark</item>

    <!-- 
         colorAccent is used as the default value for colorControlActivated
         which is used to color widgets 
    -->
    <item name="colorAccent">@color/my_fancy_color</item>

    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight & colorSwitchThumbNormal. -->
</style>

我可以用来制作自己的版本的可绘制对象在哪里?

我不建议直接更改可绘制对象,但它们位于

sdk/platforms/android-21/data/res/drawable-XXXX

并且文件被称为

btn_switch_to_off_mtrl_XXXXX.9.png

btn_switch_to_on_mtrl_XXXXX.9.png

switch_track_mtrl_alpha.9.png

于 2014-12-11T05:39:18.890 回答
6

要完成 JDJ 的回答:

AppCompat 中的 drawable-hdpi 中存在损坏文件的错误:

https://code.google.com/p/android/issues/detail?id=78262

要修复它,只需使用以下 2 个文件覆盖它:

https://github.com/lopespm/quick-fix-switchcompat-resources

将它们添加到您的 drawable-hdpi 目录。

XML

<android.support.v7.widget.SwitchCompat
android:id="@+id/dev_switch_show_dev_only"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>

在 Java 中什么都不需要

于 2015-01-06T16:54:05.313 回答
3

就我而言,我只想设置特定开关的样式,而不是应用程序中的所有开关。这是我使用 AppCompat-v7:23 的方法

xml布局:

<android.support.v7.widget.SwitchCompat
                android:id="@+id/switchAffiliateMember"
                android:theme="@style/Sugar.Switch.Affiliate"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:textOff="No"
                android:textOn="Yes" />

v21/styles.xml:

<style name="Sugar.Switch.Affiliate" parent="Base.Widget.AppCompat.CompoundButton.Switch">
    <item name="colorSwitchThumbNormal">@color/red</item>
    <item name="colorAccent">@color/white</item>
</style>

colorSwitchThumbNormal 是“关闭”状态,colorAccent 是“开启”状态。请注意,它们都没有“android”命名空间前缀,我不明白为什么,但它只对我有效。

于 2015-11-10T17:02:45.130 回答