我正在使用一个标准的开关控制与全息。轻主题在ICS应用程序。

我想改变切换按钮的高亮或状态颜色,从标准的浅蓝色到绿色。

这应该很容易,但我似乎不知道该怎么做。


当前回答

在Android Lollipop和以上版本中,在你的主题样式中定义它:

<style name="BaseAppTheme" parent="Material.Theme">
    ...
    <item name="android:colorControlActivated">@color/color_switch</item>
</style>

其他回答

到目前为止,最好从AppCompat中使用SwitchCompat。v7图书馆。然后,您可以使用简单的样式来更改组件的颜色。

values/themes.xml:

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

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

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

    <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight, and colorSwitchThumbNormal. -->

</style>

参考:Android开发者博客

编辑:

它应该正确应用的方式是通过android:theme="@style/ theme。MyTheme” 这也可以应用到父样式,如EditTexts, RadioButtons, Switches, CheckBoxes和ProgressBars:

<style name="My.Widget.ProgressBar" parent="Widget.AppCompat.ProgressBar">

<style name="My.Widget.Checkbox" parent="Widget.AppCompat.CompoundButton.CheckBox">

创建可绘制的newthumb。xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="@color/Green" android:state_checked="true"/>
  <item android:color="@color/Red" android:state_checked="false"/>
</selector>

创建可绘制的newtrack。xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:color="@color/black" android:state_checked="true"/>
  <item android:color="@color/white" android:state_checked="false"/>
</selector>

并添加到Switch中:

<Switch
  android:trackTint="@drawable/newtrack"
  android:thumbTint="@drawable/newthumb"
/>

使用app:trackTint和app:thumbTint来切换compat androidx -见@Ehsan Rosdi的评论。

此外,它完全可以只做一个可绘制文件(“switchcolors.xml”),并将其用于trackTint和thumbTint。

这招对我很管用——

1.values/styles.xml中的代码:

 <style name="SwitchTheme" parent="Theme.AppCompat.Light">
    <item name="android:colorControlActivated">#148E13</item>
</style>

2.在布局文件的交换机中添加以下代码行-:

android:theme="@style/SwitchTheme"

要在不使用style. XML或Java代码的情况下更改Switch样式,您可以将Switch定制为布局XML:

<Switch
        android:id="@+id/checkbox"
        android:layout_width="wrap_content"
        android:thumbTint="@color/blue"
        android:trackTint="@color/white"
        android:checked="true"
        android:layout_height="wrap_content" />

它的属性android:thumbTint和android:trackTint,允许你自定义颜色

下面是这个XML的可视化结果:

Android Studio 3.6解决方案:

yourSwitch.setTextColor(getResources().getColor(R.color.yourColor));

更改颜色XML文件定义值(yourColor)中的文本颜色。