the*_*0ID 7 android android-event
我有一个视图需要处理onTouch手势和 onClick事件.实现这个目标的正确方法是什么?
我有一个onTouchListener和一onClickListener组视图.每当我触摸视图时,首先onTouch触发事件,然后触发onClick.但是,从onTouch事件处理程序我必须返回true或false.返回true意味着正在使用该事件,因此android事件系统将不再传播该事件.
因此,onClick永远不会生成事件,至少在我的事件处理程序中onClick返回时,我的侦听器永远不会被触发.另一方面,返回时没有选项,因为这会阻止侦听器接收为识别手势所必需的任何其他事件.解决这个问题的常用方法是什么?trueonTouchfalseonTouch
在你的GestureDetector中,你可以直接调用callOnClick().请注意,View.callOnClick API需要API级别15.只需试一试即可.
// Create a Gesturedetector
GestureDetector mGestureDetector = new GestureDetector(context, new MyGestureDetector());
// Add a OnTouchListener into view
m_myViewer.setOnTouchListener(new OnTouchListener()
{
@Override
public boolean onTouch(View v, MotionEvent event)
{
return mGestureDetector.onTouchEvent(event);
}
});
private class MyGestureDetector extends GestureDetector.SimpleOnGestureListener
{
public boolean onSingleTapUp(MotionEvent e) {
// ---Call it directly---
callOnClick();
return false;
}
public void onLongPress(MotionEvent e) {
}
public boolean onDoubleTap(MotionEvent e) {
return false;
}
public boolean onDoubleTapEvent(MotionEvent e) {
return false;
}
public boolean onSingleTapConfirmed(MotionEvent e) {
return false;
}
public void onShowPress(MotionEvent e) {
LogUtil.d(TAG, "onShowPress");
}
public boolean onDown(MotionEvent e) {
// Must return true to get matching events for this down event.
return true;
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, final float distanceX, float distanceY) {
return super.onScroll(e1, e2, distanceX, distanceY);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
// do something
return super.onFling(e1, e2, velocityX, velocityY);
}
}
Run Code Online (Sandbox Code Playgroud)
如果你使用onTouchListener,你不必使用onClickListener.在onClickListener它的作用是让触摸事件,并检查事件动作和检测到点击.所以,如果你想做一些工作onClick.你可以onTouchListener通过过滤动作来做到这一点.
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
//this is touch
}
if (event.getAction() == MotionEvent.ACTION_UP) {
//this is click
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19293 次 |
| 最近记录: |