Android 更改开关的“开启”颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11253512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change "on" color of a Switch
提问by JamesSugrue
I'm using a standard Switch control with the holo.light theme in a ICS app.
我在 ICS 应用程序中使用带有holo.light 主题的标准开关控件。
I want to change the highlighted or on state color of the Toggle Button from the standard light blue to green.
我想将切换按钮的突出显示或开启状态颜色从标准浅蓝色更改为绿色。
This should be easy, but I can't seem to work out how to do it.
这应该很容易,但我似乎无法弄清楚如何去做。
采纳答案by SubChord
As of now it is better to use SwitchCompat from the AppCompat.v7 library. You can then use simple styling to change the color of your components.
目前最好使用 AppCompat.v7 库中的 SwitchCompat。然后,您可以使用简单的样式来更改组件的颜色。
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>
EDIT:
编辑:
The way in which it should be correctly applied is through android:theme="@style/Theme.MyTheme"
and also this can be applied to parent styles such as EditTexts, RadioButtons, Switches, CheckBoxes and ProgressBars:
正确应用它的方式是通过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">
回答by Hitesh Sahu
Late to party but this is how I did
聚会迟到,但这就是我所做的
Style
风格
<style name="SCBSwitch" parent="Theme.AppCompat.Light">
<!-- active thumb & track color (30% transparency) -->
<item name="colorControlActivated">#46bdbf</item>
<!-- inactive thumb color -->
<item name="colorSwitchThumbNormal">#f1f1f1
</item>
<!-- inactive track color (30% transparency) -->
<item name="android:colorForeground">#42221f1f
</item>
</style>
Colors
颜色
Layout
布局
<android.support.v7.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:checked="false"
android:theme="@style/SCBSwitch" />
Result
结果
See change of colors for enables and disabled switch
查看启用和禁用开关的颜色变化
回答by arlomedia
This is working for me (requires Android 4.1):
这对我有用(需要 Android 4.1):
Switch switchInput = new Switch(this);
int colorOn = 0xFF323E46;
int colorOff = 0xFF666666;
int colorDisabled = 0xFF333333;
StateListDrawable thumbStates = new StateListDrawable();
thumbStates.addState(new int[]{android.R.attr.state_checked}, new ColorDrawable(colorOn));
thumbStates.addState(new int[]{-android.R.attr.state_enabled}, new ColorDrawable(colorDisabled));
thumbStates.addState(new int[]{}, new ColorDrawable(colorOff)); // this one has to come last
switchInput.setThumbDrawable(thumbStates);
Note that the "default" state needs to be added last as shown here.
请注意,需要最后添加“默认”状态,如下所示。
The only problem I see is that the "thumb" of the switch now appears larger than the background or "track" of the switch. I think that's because I'm still using the default track image, which has some empty space around it. However, when I attempted to customize the track image using this technique, my switch appeared to have a height of 1 pixel with just a sliver of the on/off text appearing. There must be a solution for that, but I haven't found it yet...
我看到的唯一问题是开关的“拇指”现在看起来比开关的背景或“轨道”大。我认为这是因为我仍在使用默认轨道图像,它周围有一些空白空间。但是,当我尝试使用这种技术自定义轨道图像时,我的开关似乎具有 1 像素的高度,只出现了一小段开/关文本。一定有解决方案,但我还没有找到......
Update for Android 5
Android 5 更新
In Android 5, the code above makes the switch disappear completely. We should be able to use the new setButtonTintListmethod, but this seems to be ignored for switches. But this works:
在 Android 5 中,上面的代码使开关完全消失。我们应该能够使用新的setButtonTintList方法,但是对于开关来说这似乎被忽略了。但这有效:
ColorStateList buttonStates = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_enabled},
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
Color.BLUE,
Color.RED,
Color.GREEN
}
);
switchInput.getThumbDrawable().setTintList(buttonStates);
switchInput.getTrackDrawable().setTintList(buttonStates);
Update for Android 6-7
Android 6-7 更新
As Cheruby stated in the comments, we can use the new setThumbTintList
and that worked as expected for me. We can also use setTrackTintList
, but that applies the color as a blend, with a result that's darker than expected in dark color themes and lighter than expected in light color themes, sometimes to the point of being invisible. In Android 7, I was able to minimize that change that by overriding the track tint mode, but I couldn't get decent results from that in Android 6. You might need to define extra colors that compensate for the blending. (Do you ever get the feeling that Google doesn't want us to customize the appearance of our apps?)
正如 Cheruby 在评论中所说的那样,我们可以使用新的setThumbTintList
并且对我来说按预期工作。我们也可以使用setTrackTintList
,但这将颜色作为混合应用,结果在深色主题中比预期更暗,在浅色主题中比预期更亮,有时甚至不可见。在 Android 7 中,我能够通过覆盖 track tint mode来最小化这种变化,但在 Android 6 中我无法获得不错的结果。您可能需要定义额外的颜色来补偿混合。(您有没有感觉到 Google 不希望我们自定义应用程序的外观?)
ColorStateList thumbStates = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_enabled},
new int[]{android.R.attr.state_checked},
new int[]{}
},
new int[]{
Color.BLUE,
Color.RED,
Color.GREEN
}
);
switchInput.setThumbTintList(thumbStates);
if (Build.VERSION.SDK_INT >= 24) {
ColorStateList trackStates = new ColorStateList(
new int[][]{
new int[]{-android.R.attr.state_enabled},
new int[]{}
},
new int[]{
Color.GRAY,
Color.LTGRAY
}
);
switchInput.setTrackTintList(trackStates);
switchInput.setTrackTintMode(PorterDuff.Mode.OVERLAY);
}
回答by Kevin ABRIOUX
To change Switch style without using style.xml or Java code, you can customize switch into layout XML :
要在不使用 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" />
It's attribute android:thumbTintand android:trackTintthat allowed you to customize color
它的属性android:thumbTint和android:trackTint允许您自定义颜色
This is the visual result for this XML :
这是此 XML 的视觉结果:
回答by francisco_ssb
Create a custom Switch and override setChecked to change color:
创建自定义 Switch 并覆盖 setChecked 以更改颜色:
public class SwitchPlus extends Switch {
public SwitchPlus(Context context) {
super(context);
}
public SwitchPlus(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SwitchPlus(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setChecked(boolean checked) {
super.setChecked(checked);
changeColor(checked);
}
private void changeColor(boolean isChecked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
int thumbColor;
int trackColor;
if(isChecked) {
thumbColor = Color.argb(255, 253, 153, 0);
trackColor = thumbColor;
} else {
thumbColor = Color.argb(255, 236, 236, 236);
trackColor = Color.argb(255, 0, 0, 0);
}
try {
getThumbDrawable().setColorFilter(thumbColor, PorterDuff.Mode.MULTIPLY);
getTrackDrawable().setColorFilter(trackColor, PorterDuff.Mode.MULTIPLY);
}
catch (NullPointerException e) {
e.printStackTrace();
}
}
}
}
回答by Greg Ennis
While answer by SubChord is correct, is doesnt really answer the question of how to set the "on" color without also affecting other widgets. To do this, use a ThemeOverlay
in styles.xml:
虽然 SubChord 的回答是正确的,但并没有真正回答如何在不影响其他小部件的情况下设置“开启”颜色的问题。为此,请ThemeOverlay
在styles.xml 中使用a :
<style name="ToggleSwitchTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorAccent">@color/green_bright</item>
</style>
And reference it in your switch:
并在您的交换机中引用它:
<android.support.v7.widget.SwitchCompat
android:theme="@style/ToggleSwitchTheme" ... />
In so doing it will ONLY affect the color of the views you want to apply it to.
这样做只会影响您想要应用它的视图的颜色。
回答by wingear
<androidx.appcompat.widget.SwitchCompat
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:thumbTint="@color/white"
app:trackTint="@drawable/checker_track"/>
And inside checker_track.xml:
在 checker_track.xml 中:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/lightish_blue" android:state_checked="true"/>
<item android:color="@color/hint" android:state_checked="false"/>
</selector>
回答by MCR
I solved it by updating the Color Filter when the Switch was state was changed...
我通过在切换状态更改时更新滤色器来解决它...
public void bind(DetailItem item) {
switchColor(item.toggle);
listSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
switchColor(b);
}
});
}
private void switchColor(boolean checked) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
listSwitch.getThumbDrawable().setColorFilter(checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
listSwitch.getTrackDrawable().setColorFilter(!checked ? Color.BLACK : Color.WHITE, PorterDuff.Mode.MULTIPLY);
}
}
回答by Golgorz
May be its a bit late, but for switch buttons, toogle button is not the answer, you must change the drawable in the xml parameter of the switch:
可能有点晚了,但是对于开关按钮,toogle 按钮不是答案,您必须更改开关的 xml 参数中的 drawable:
android:thumb="your drawable here"
回答by ???? ????
make drawable "newthumb.xml"
制作可绘制的“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>
and make drawable "newtrack.xml"
并制作可绘制的“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>
and add it in Switch :
并将其添加到 Switch 中:
<Switch
android:trackTint="@drawable/newtrack"
android:thumbTint="@drawable/newthumb"
/>