2017-08-17 30 views
0

我使用下面的代码创建了圆形切换按钮。 我想根据切换状态更改按钮的颜色 -如何更改切换按钮的颜色而不使用代码

我怎样可以不用将代码添加到Java的活动(像在“textoff” &“纹元”,我可以添加代码编译只有xml,并且不需要将代码添加到后面的java代码中)

是否有可能?

<ToggleButton 
    android:id ="@+id/actionToggleButton" 
    android:layout_width="150dp" 
    android:layout_height="150dp" 
    android:background="@drawable/button_bg_round" 
    android:textoff="off" 
    android:texton="on" 
    android:padding="15dp" 
    /> 


<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
     <item> 
     <shape android:shape="oval"> 
       <stroke android:color="#1E90FF" android:width="5dp" /> 
       <solid android:color="#87CEEB"/> 
       <size android:width="150dp" android:height="150dp"/> 
     </shape> 
    </item> 
</selector> 
+1

你可以看看这个[https://stackoverflow.com/questions/11978880/how-to-change-color-of-the-toggle-button](https://stackoverflow.com/questions/11978880/how -to-改变颜色的最肘节按钮) – KeLiuyue

回答

2

你可以在你style.xml您切换按钮定义自定义样式,例如:

<style name="ToggleButton.CustomTheme" parent="Theme.AppCompat.Light"> 
    <item name="colorControlNormal">@color/your_color</item> 
    <item name="colorControlActivated">@color/your_color</item> 
</style> 

则样式应用到您的切换按钮

<ToggleButton 
    android:id ="@+id/actionToggleButton" 
    android:layout_width="150dp" 
    android:layout_height="150dp" 
    android:background="@drawable/button_bg_round" 
    android:textoff="off" 
    android:texton="on" 
    android:padding="15dp" 
    android:theme="@style/ToggleButton.CustomTheme" 
    /> 

而不是colorControlActivated它可能是colorAccent,我现在无法测试。

希望这会有所帮助。