2012-04-17 37 views
4

我正在编写一个需要响应触摸事件的Android应用程序。我希望我的应用程序将我的列表项目的颜色更改为自定义颜色。我写了下面的代码,但只有MotionEvent.ACTION_DOWN部分正在工作。 LogCat显示ACTION_CANCELACTION_UP根本不被调用。你能帮我理解为什么我的代码不工作。不显示MotionEvent.ACTION_UP或MotionEvent.ACTION_CANCEL

这是我的代码...

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

你能不能把日志作为方法的第一行(第一个'if'语句之前)。该方法是否在您期望的所有时间都被触发?此外,如果你正在移动,可能事件得到*批处理*,如http://developer.android.com/reference/android/view/MotionEvent.html – wattostudios 2012-04-17 13:30:03

回答

19

如果返回falseonTouch方法,没有进一步的事件被传递给听众。至少在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; 
} 
}); 
+0

中所述。嗨Rajesh,我喜欢有同样的问题相同类型的代码。它不适合我,即使我回复真实。如果我保持索引pring操作我没有得到ACTION_UP(1),如果我尝试拖动按钮。那么你能否提出一些替代解决方案? – Raj 2012-05-10 09:21:49

+0

你可以把它作为一个新的问题发布并提供足够的细节吗?你的问题可能完全不同。 – Rajesh 2012-05-10 09:32:21

+0

嗨Rajesh,感谢您的重播。对我来说ACTION_UP没有被调用。但它的工作,如果我添加ACTION_CANCEL。谢谢您的帮助。 – Raj 2012-05-14 09:54:19