Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
});
like image 778
prometheuspk Avatar asked Dec 01 '22 00:12

prometheuspk


1 Answers

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;
}
});
like image 198
Rajesh Avatar answered Dec 05 '22 08:12

Rajesh