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

//根据坐标返回触摸到的View
private View getTouchTarget(View rootView, int x, int y) {
View targetView = null;
// 判断view是否可以聚焦
ArrayList<View> 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);
}

posted on 2017-10-09 10:46  guangdeshishe  阅读(827)  评论(0编辑  收藏  举报

导航