Android 判斷觸控點是否在某個view內部,解決子childView與parentView的touch事件衝突
阿新 • • 發佈:2019-01-11
事件衝突在觸控事件經常發生,這裡記一個解決子view與parent的touch事件衝突的小方法:
原理,對觸控點進行位置判斷,是否在目標View內部。
第一步:判斷位置
private boolean isTouchPointInView(View targetView, int xAxis, int yAxis) {
if (targetView== null) {
return false;
}
int[] location = new int[2];
targetView.getLocationOnScreen(location);
int left = location[0];
int top = location[1];
int right = left + targetView.getMeasuredWidth();
int bottom = top + targetView.getMeasuredHeight();
if (yAxis >= top && yAxis <= bottom && xAxis >= left
&& xAxis <= right) {
return true;
}
return false;
}
第二步:在parentView中,進行事件攔截
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int x = (int) ev.getRawX();
int y = (int) ev.getRawY();
if (isTouchPointInView(targetView, x, y)) {
// insided,do somethings you like
return super.dispatchTouchEvent(ev);
}else{
// outsided,do somethings you like
return super.dispatchTouchEvent(ev);
}
}