简体   繁体   中英

How to distinguish between ACTION_UP and actual click via onTouchListener?

I have an ImageView with an icon. I want to be able to:

1 . Change the icon on hover (meaning - change to icon #2 on ACTION_DOWN but also change it back to icon #1 on ACTION_UP )
2 . Trigger an onClick function (meaning - call another function when the ImageView was clicked )

This is how my onTouch looks like right now:

@Override
public boolean onTouch(View v, MotionEvent event) {

    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            // CHANGE TO IMAGE #2
            break;

        case MotionEvent.ACTION_UP:
            // CHANGE TO IMAGE #1
            break;
    }

    return true;
}

The problem is - I can't know when the user pressed my ImageView and then left its area while still pressing down . I hope I explaied it well. I mean that ACTION_UP does not always imply that the user intended to click the View. How can I know for sure when the ImageView was clicked and not just hovered (and still be able to change the icon on hover)?

Will be better if you'll use selector . You can read more about StateList . There are many examples in Internet how it use.

Use Selector Drawable Something Like This.

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

    <!-- default -->
    <item android:drawable="@drawable/btn_bg" android:state_focused="false" android:state_pressed="false" />

    <!-- button focused -->
    <item android:drawable="@drawable/btn_bg_focus_new" android:state_focused="true" android:state_pressed="false" />

    <!-- button pressed -->
    <item android:drawable="@drawable/btn_bg_focus_new" android:state_focused="false" android:state_pressed="true" />
</selector>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM