I have a button_animation.xml in my res/drawable folder for showing different button states (default, pressed, focused). I reference button_animation.xml in a button in my layout file. It works perfectly, except for when I set an onTouchListener on the button that is actually being pressed. Below is my code.
button_animation.xml
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/button_pressed"
android:state_pressed="true" />
<item android:drawable="@drawable/button_focused"
android:state_focused="true" />
<item android:drawable="@drawable/button_default" />
</selector>
layout.xml
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/button_animation" />
Code that causes the animation to break
Button button = (Button) findViewById(R.id.button1);
button.setOnTouchListener(this);
Am I not able to show the button state as the documentation suggests and handle onClick at the same time for any particular view?
Documentation: http://developer.android.com/guide/topics/ui/controls/button.html
Thanks,
Jason
This answer is pretty old, but just in case anyone comes searching for how to do this, here's how you can do it. @Shadesblade was close, but not quite there.
public boolean onTouch(View button, MotionEvent theMotion) {
switch (theMotion.getAction()) {
case MotionEvent.ACTION_DOWN:
button.setPressed(true);
break;
case MotionEvent.ACTION_UP:
button.setPressed(false);
break;
}
return true;
}
This way you can use an xml selector drawable and still toggle the state with an ontouchlistener.
Also make sure that the view "button" is clickable (Button class is clickable by default but if you are using some other view/viewgroup you made need to delcare this in the xml).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With