我正在编写一个Android应用程序,需要响应触摸事件。我希望我的应用程序将列表项的颜色更改为自定义颜色。我已经编写了以下代码,但只有MotionEvent.ACTION_DOWN部分可以正常工作。LogCat显示根本没有调用ACTION_CANCEL和ACTION_UP。你能帮助我理解为什么我的代码不能工作吗?
这是我的代码。
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;
}
});发布于 2012-04-17 22:14:34
如果从onTouch方法返回false,则不会进一步将事件传递给侦听器。至少在event.getAction() == MotionEvent.ACTION_DOWN的情况下,你应该返回true。
如下所示重构您的代码:
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;
}
});https://stackoverflow.com/questions/10192122
复制相似问题