0

So I have an image button and I want to have two states on it. It will work like a bookmark button which has two states. If the user presses the button then it changes the image and if it re-presses the button then I want the original image back.

Is that possible? Is there an easier way using another type of button? Thank you

George Artemiou
  • 3,076
  • 2
  • 19
  • 36

4 Answers4

2

Try changing the topic to :"What kind of Button can toggle/change states?"

Seems like you need ToggleBotton

<ToggleButton                  
        android:layout_width="wrap_content"
        android:layout_height="26dp"
        android:background="@color/button_colors"
        android:button="@null"
        android:textOff="@null"
        android:textOn="@null" />

And this xml defines the colors/images of the button at rest/pressed states, put it in res/color/button_colors.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="false" android:drawable="@drawable/button_rest"/>
<item android:state_checked="true" android:drawable="@drawable/button_on" />    
</selector>
Rotemmiz
  • 7,933
  • 3
  • 36
  • 36
  • thank you. So after that I just need to attach a listener and set the actions.. I can get the state of the button rigth? and depending on that I can perform actions. – George Artemiou Feb 28 '12 at 01:26
0

Yes, you can use regular buttons also. First make a selector XML file in the res/drawable directory. Example:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_enabled="true" android:state_selected="true"
android:drawable="@drawable/selectedimage"/>

<item android:state_enabled="true" android:state_selected="false"
android:drawable="@drawable/notselectedimage"/>

</selector>

In the button definition in the layout xml, you just add this attribute:

android:background="@drawable/myselectorxmlfile"

And then you programmatically set the selected states yourself (in a onClickListener) and the button images will change background state.

button.setSelected(true) // or false;
gorn
  • 8,097
  • 5
  • 37
  • 44
0

I guess you can use Toggle Button and hope it'll solve your issue. Just have a look at a simple xml code of it:

<ToggleButton
              android:id="@+id/tglbtn"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:textOn="ON"
              android:textOff="OFF"
              />

And Just check the answer given here in this link: Android: Specify two different images for togglebutton using XML

Also, I've posted a simple tutorial about Toggle Button. Just have a look at my humble blog if you find it helpful. Here is link: http://androiddesk.wordpress.com/2012/03/10/toggle-button-in-android/

Community
  • 1
  • 1
Deepthi G
  • 79
  • 2
  • 10