您的位置:首页 > 其它

判断当前Event触点是否在指定区域之内的两种方法

2013-08-16 19:31 465 查看
1.根据屏幕绝对坐标

public static boolean checkDownPointerInView(View view, float x, float y) {
int[] location2 = new int[2];
view.getLocationOnScreen(location2);
if (x >= location2[0] && x <=  location2[0] + view.getWidth() && y >= location2[1] && y <= location2[1] + view.getHeight()) {
return true;
}
return false;
}


使用示例(对于一个popupwindow,如果触点在其外,则关闭自己:
public boolean onTouch(View v, MotionEvent event) {
int action=event.getAction();
switch(action){
case MotionEvent.ACTION_DOWN:
float x=event.getRawX();
float y=event.getRawY();
if(!PositionUtils.checkDownPointerInView(viewMain, x, y)){
mPopupWindow.dismiss();
return true;
}
}
return false;
}


2.通过一个view对应的长方形最为媒介。
public boolean isXYInRec(float x,float y,Rect r)
{
if(r.left <= x&& r.right >= x&&r.top <= y&& r.bottom >= y)
{
return true;
}
return false;
}


使用示例:

     需要记住的是,代码中的childView必须是fatherView的子控件,或者是father背景drawable中一个需要绘画的bitmap元素等这种情况。 fatherView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
float x=event.getX();
float y=event.getY();
Rect r = new Rect();
childView.getGlobalVisibleRect(r);
if(isXYInRec(x,y,r){
//TODO
}
return false;
}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息