The color you specify for colorAccent will be used to color the widgets in your app such as SwitchCompats, EditTexts, RadioButtons, etc.
所以你的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>
3 回答
现在使用新的appcompat-v7:21,着色小部件非常简单 .
只要您使用appcompat-v7:21,就可以用
SwitchCompat
小部件替换所有旧的Switch
小部件 . 因此,在xml布局中,使用android.support.v7.widget.SwitchCompat
而不是使用旧的Switch
标记 .然后在styles.xml中,确保您应用的父主题是
Theme.AppCompat
主题,例如Theme.AppCompat.Light
.最后,关键是为
colorAccent
指定自己的值:The color you specify for colorAccent will be used to color the widgets in your app such as SwitchCompats, EditTexts, RadioButtons, etc.
所以你的styles.xml可能看起来像:
我不建议直接改变drawable,但它们位于
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
完成JDJ的答案:
AppCompat中的drawable-hdpi中存在损坏文件的错误:
https://code.google.com/p/android/issues/detail?id=78262
要修复它,只需使用这两个文件覆盖它:
https://github.com/lopespm/quick-fix-switchcompat-resources
将它们添加到drawable-hdpi目录中 .
XML
Java中没有必要
在我的情况下,我只想设置一个特定的开关,而不是应用程序中的所有开关 . 以下是我使用AppCompat-v7:23的方法
xml布局:
V21 / styles.xml:
colorSwitchThumbNormal是“off”状态,colorAccent是“on”状态 . 请注意,这些都没有“android”命名空间前缀,我不明白为什么,但它只适用于我这种方式 .