0

I have a ToggleButton that uses a selector to choose between 2 images (checked and unchecked).

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true"
          android:drawable="@drawable/img_piece1" /> <!-- pressed -->
    <item     android:drawable="@drawable/img_piece2" /> <!-- default/unchecked -->
</selector>

Is there a way to retrieve the current drawable resource (checked/unchecked) of the toggle button in code? I tried using the ToggleButton.getBackground(), however this only seems to return the default Drawable always.

source.rar
  • 8,002
  • 10
  • 50
  • 82
  • I did come across this (http://stackoverflow.com/questions/3147299/android-imagebutton-determine-what-resource-is-currently-set) with some more searching, and am looking into using setTag() and getTag(). – source.rar Jun 22 '11 at 03:27

3 Answers3

3

I figured out how to do this and so am answering my own question. :)

Apparently the current drawable can be retrieved with ToggleButton.getBackground().getCurrent()

Hope it helps.

source.rar
  • 8,002
  • 10
  • 50
  • 82
1

i was in same situation few days ago.. but made my way out by giving its TEXT ON ="." and TextOFF as "" ie blank... that dot wont be seem on that image (probably) coz mine did not. works well then check the text on toggle button.

Shashank Degloorkar
  • 3,151
  • 4
  • 32
  • 50
  • Well, I am already using the ToggleButton.isChecked() to determine the current state and using that to specify the correct image. However I would like to get the current image without resorting to checking the state or checking some other attr if possible. As that "may" lead to a disconnect later between the image used by the selector (if I forget to update in either place). – source.rar Jun 22 '11 at 03:21
  • Hey, found a better way to do this. Check my answer below for details. – source.rar Jun 22 '11 at 07:08
0

Though I haven't ever played with it, you may want to take a look at getDrawableState(). It may have what you're looking for.

Jason Robinson
  • 31,005
  • 19
  • 77
  • 131
  • I had a look but just can't seem to figure out how to use the returned int array[] values to get the Drawable. Dumping the values showed the following 3 values (for the toggle button in the checked state), [0]=0x101009d, [1]=0x101009e ,[2]=0x10100a0. Which according to R.attr are 'state_window_focused', 'state_enabled', 'state_checked' – source.rar Jun 22 '11 at 03:16