Android button hover event
Asked Answered
B

1

5

I use a XML file to display a button with 2 states (normal, pressed). How can I find out when the button is pressed? Is there an event like onClick --> onPressed or how can I find it out?

Here is the XML file I use:

<?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/buttonbluepressed" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/buttonbluepressed" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/buttonbluepressed" />
    <item android:drawable="@drawable/buttonblue"/>
</selector>

And here is how I use it:

<Button
    android:id="@+id/button_choose"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="@drawable/choose_button"
    android:onClick="onButtonClicked"
    android:text="@string/button_choose" />
Bridgid answered 30/6, 2012 at 8:18 Comment(0)
H
17

you can use setOnTouchListener as:

button.setOnTouchListener(new OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if(event.getAction() == MotionEvent.ACTION_DOWN){
                    //Button Pressed
                }
                if(event.getAction() == MotionEvent.ACTION_UP){
                     //finger was lifted
                }
                return false;
            }
        });
Helfant answered 30/6, 2012 at 8:20 Comment(2)
Thank you for your answer. It was what I was looking for. I had to change the return to false otherwise the button state image for pressed was not shown.Bridgid
Thank you again. Yea, I had to wait at least 10 min to mark the answer as correct...Bridgid

© 2022 - 2024 — McMap. All rights reserved.