[英]not showing MotionEvent.ACTION_UP or MotionEvent.ACTION_CANCEL
I am writing an Android app that needs to respond to touch events. 我正在编写一个需要响应触摸事件的Android应用。 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. 我编写了以下代码,但只有MotionEvent.ACTION_DOWN
部分正在运行。 The LogCat shows that ACTION_CANCEL
and ACTION_UP
aren't called at all. LogCat显示ACTION_UP
没有调用ACTION_CANCEL
和ACTION_UP
。 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. 如果从onTouch
方法返回false
, onTouch
其他事件传递给侦听器。 You should return true
at least in case of event.getAction() == MotionEvent.ACTION_DOWN
. 至少在event.getAction() == MotionEvent.ACTION_DOWN
情况下,你应该返回true
。
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;
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.