How to make a custom button for pressed and released at android?
I know there are many questions of this kind here, but I really dont know the reason that my code is not working.
I'm trying to make a button with three states: normal, pressed and released. When I say released, I mean that I would like to make this like a toogle button, with the states active
and not active
.
When I release the button, it returns to the default state. I would like to change the image by click, as a checkButton works.
I tried this:
http://blog.androgames.net/40/custom-button-style-and-theme/
http://www.gersic.com/blog.php?id=56
Android: How to Create a Custom button widget
http://techdroid.kbeanie.com/2010/03/custom-buttons-on-android.html
custom_buttom.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/focussed" />
<item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/focussedandpressed" />
<item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/pressed" />
<item android:drawable="@drawable/default" />
</selector>
layout.xml:
<Button android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="@+id/menu"
开发者_StackOverflow中文版 android:layout_weight="1" android:background="@drawable/custom_button"></Button>
You are using android:state_focused
and android:state_pressed
.
What about android:state_checked?
You want custom something like Checkbox, right? In that case, you need two image for state check true and false, and a transparent file for background (which have no content, just has the same size as other images). Create two drawable selector file have content like this:
background_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/your_bg" />
</selector>
state_selector.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:state_focused="true"
android:drawable="@drawable/checkbox_on" />
<item android:state_checked="false" android:state_focused="true"
android:drawable="@drawable/checkbox_off" />
<item android:state_checked="false"
android:drawable="@drawable/checkbox_off" />
<item android:state_checked="true"
android:drawable="@drawable/checkbox_on" />
</selector>
Put these xml to your drawable folder, and in your layout, create a checkbox:
<CheckBox
android:layout_width="50dip"
android:layout_height="50dip"
android:background="@drawable/background_selector"
android:button="@drawable/state_selector"
/>
Hope this help ^_^
精彩评论