简体   繁体   中英

not showing MotionEvent.ACTION_UP or MotionEvent.ACTION_CANCEL

I am writing an Android app that needs to respond to touch events. I want my app to change the color of my list item to a custom color. I have written the following code, but only the MotionEvent.ACTION_DOWN section is working. The LogCat shows that ACTION_CANCEL and ACTION_UP aren't called at all. Could you please help me understand why my code isn't working.

This is my code...

view.setOnTouchListener(new OnTouchListener() {

    public boolean onTouch(View v, MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_UP) {
            view.setBackgroundColor(Color.rgb(1, 1, 1));
            Log.d("onTouch", "MotionEvent.ACTION_UP" );
        }
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            view.setBackgroundColor(Color.rgb(23, 128, 0));
            Log.d("onTouch", "MotionEvent.ACTION_DOWN" );
        }
        if (event.getAction() == MotionEvent.ACTION_CANCEL) {
            view.setBackgroundColor(Color.rgb(1, 1, 1));
            Log.d("onTouch", "MotionEvent.ACTION_CANCEL" );
        }
        return false;
    }
});

If you return false from onTouch method, no further events get delivered to the listener. You should return true at least in case of event.getAction() == MotionEvent.ACTION_DOWN .

Refactor your code as given below:

view.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_UP) {
    view.setBackgroundColor(Color.rgb(1, 1, 1));
    Log.d("onTouch", "MotionEvent.ACTION_UP" );
}
if (event.getAction() == MotionEvent.ACTION_DOWN) {
    view.setBackgroundColor(Color.rgb(23, 128, 0));
    Log.d("onTouch", "MotionEvent.ACTION_DOWN" );
    return true;
}

if (event.getAction() == MotionEvent.ACTION_CANCEL) {
    view.setBackgroundColor(Color.rgb(1, 1, 1));
    Log.d("onTouch", "MotionEvent.ACTION_CANCEL" );
}
return false;
}
});

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