自定义View在构造器初始化时设置了一个OnClickListener的监听器,但是如果在OnTouchEvent() 中返回true就没有办法回调onClick()?
// 一个简单的自定义View,让View跟随手指滑动,同时点击时弹出Toast
public class DragView2 extends View implements View.OnClickListener {
private static final String TAG = "DragView";
private float mLastX;
private float mLastY;
public DragView2(Context context) {
this(context, null);
}
public DragView2(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DragView2(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
setBackgroundColor(getResources().getColor(R.color.colorPrimary));
Log.d(TAG, "DragView2: ");
setOnClickListener(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
int offsetX = (int) (event.getX() - mLastX);
int offsetY = (int) (event.getY() - mLastY);
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
// 使View本身开始移动
offsetLeftAndRight(offsetX);
offsetTopAndBottom(offsetY);
break;
case MotionEvent.ACTION_UP:
mLastX = event.getX();
mLastY = event.getY();
break;
}
// return true 无法触发点击事件;return false时无法发生滑动 ;
// return super.onTouchEvent(event);才能触发这两个事件
// 为什么?
return super.onTouchEvent(event);
}
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: ");
Toast.makeText(getContext(), "onClick", Toast.LENGTH_SHORT).show();
}
}
返回true 不是表示此触摸事件已被消化,为何只有 return super.onTouchEvent(event);
,才能同时保留滑动和点击事件?
OnClickListener.onClick()
是在原生的View.onTouchEvent()
方法里面回调的, 你自己重写了这个方法, 而且不调用super.onTouchEvent(event)
的话当然就不会回调onClick()
The way.The onClick method is called in the onTouchEvent method. You may not understand the meaning of overriding. Are you not using super to call the onTouchEvent method of the parent class? onClick will not be executed.
Also, you may not understand the event distribution mechanism. I don’t believe that a programmer who doesn’t understand event distribution can customize View. Regarding event distribution, you can refer to the following article: http://m.blog.csdn.net/articl...