25

To create a custom ToggleButton, I've defined a new style in /res/values/styles.xml:

<style name="myToggleButton">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:textColor">#000000</item>
    <item name="android:background">@drawable/my_toggle_button</item>
</style>

and I then use a selector to specify how the button's states look in /res/drawable/my_toggle_button.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true">
        <shape>
            [...]
        </shape>
    </item>
    <item android:state_checked="false"
        <shape>
            [...]
        </shape>
    </item>
</selector>

How can I modify this setup to toggle the text color of the button when the state changes?

1''
  • 26,823
  • 32
  • 143
  • 200
  • in shape scope, give color paremeters want you want and delete background in style.xml. – Tugrul Dec 28 '12 at 05:58
  • I think this link is useful for your problem: http://stackoverflow.com/questions/7096599/how-to-change-the-text-color-of-an-android-tooglebutton-on-state-change – secretlm Dec 28 '12 at 08:55
  • Based on experimentation with auto-complete in Eclipse, that link does not give valid syntax. The only possible way to specify a colour is `` in the scope of ``. It doesn't change the text colour, though. – 1'' Dec 28 '12 at 16:47

1 Answers1

81

Create a similar state list for the text colors you would like, and place it in res/color, e.g.

res/color/toggle_color.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:color="#070" />
    <!-- Default State -->
    <item android:color="#A00" />
</selector>

Then set this resource as the text color of the button:

<item name="android:textColor">@color/toggle_color</item>

P.S., it's good practice to have the last item in a selector not have any state flags attached (i.e. a default state) rather than defining it with the inverse of the above states.

davnicwil
  • 28,487
  • 16
  • 107
  • 123
devunwired
  • 62,780
  • 12
  • 127
  • 139
  • 2
    very helpful answer - but I found it didn't run only because upper case characters aren't allowed in the filename (API version 18 at least) - made edit :) – davnicwil Oct 21 '13 at 23:18