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;
}
});
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