问题
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
回答1:
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>
回答2:
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;
回答3:
These links might help you.. http://developer.android.com/resources/tutorials/views/hello-formstuff.html and http://developer.android.com/reference/android/widget/ToggleButton.html
回答4:
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/
来源:https://stackoverflow.com/questions/9403349/what-kind-of-button-can-toggle-change-states-in-android