Yanshof
Yanshof

Reputation: 9926

how to change the toggle button color without a code behind

i created round toggle button using code below. i want to change the color of the button according to the toggle state -

How can i do it without add code to the java activity ( something like the build in 'textoff' & 'texton' that i can add code only to the xml and no need to add code to the java code behind )

Is it possible ?

 <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>

Upvotes: 0

Views: 1449

Answers (1)

Cochi
Cochi

Reputation: 2209

You can defined a custom style in your style.xml for your ToggleButton , for example :

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

Then apply the style to your ToggleButton

<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"
  />

Instead of colorControlActivated it is may be colorAccent, i can't test for now.

Hope this helps.

Upvotes: 2

Related Questions