android 根据坐标返回触摸到的View

//根据坐标返回触摸到的View
private View getTouchTarget(View rootView, int x, int y) {
View targetView = null;
// 判断view是否可以聚焦
ArrayList touchableViews = rootView.getTouchables();
for (View touchableView : touchableViews){
if (isTouchPointInView(touchableView, x, y)){
targetView = touchableView;
break;
}
}
return targetView;
}

//(x,y)是否在view的区域内
private boolean isTouchPointInView(View view, int x, int y) {
if (view == null){
return false;
}
int[] position = new int[2];
view.getLocationOnScreen(position);
int left = position[0];
int top = position[1];
int right = left + view.getMeasuredWidth();
int bottom = top + view.getMeasuredHeight();
if (x >= left && x <= right && y >= top && y <= bottom){
return true;
}
return false;
}

示例:
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
//获取当前触摸到的View
final View touchedView = getTouchTarget(mContentView,(int) ev.getX(), (int) ev.getY());
return super.dispatchTouchEvent(ev);
}

转载于:https://www.cnblogs.com/agilezhu/p/7640025.html

你可能感兴趣的:(android 根据坐标返回触摸到的View)