在應(yīng)用中有時需要判斷觸摸事件的位置是否在某個 View 內(nèi)闰歪,可以按照如下方法判斷:
1. 獲取 View 的坐標(biāo)
Android 中使用矩形表示一個 View 的坐標(biāo)哄陶,獲取 View 在屏幕中的位置并將其轉(zhuǎn)換成矩形坐標(biāo):
/**
* 計(jì)算指定的 View 在屏幕中的坐標(biāo)粟瞬。
*/
public static RectF calcViewScreenLocation(View view) {
int[] location = new int[2];
// 獲取控件在屏幕中的位置寝优,返回的數(shù)組分別為控件左頂點(diǎn)的 x、y 的值
view.getLocationOnScreen(location);
return new RectF(location[0], location[1], location[0] + view.getWidth(),
location[1] + view.getHeight());
}
2. 獲取觸摸事件相對于屏幕的位置:
// MotionEvent event;
// event.getX(); 獲取相對于控件自身左上角的 x 坐標(biāo)值
// event.getY(); 獲取相對于控件自身左上角的 y 坐標(biāo)值
float x = event.getRawX(); // 獲取相對于屏幕左上角的 x 坐標(biāo)值
float y = event.getRawY(); // 獲取相對于屏幕左上角的 y 坐標(biāo)值
3. 使用 Rect.contains(float, float) 判斷觸摸事件是否在 View 內(nèi):
// View view;
RectF rect = calcViewScreenLocation(view);
boolean isInViewRect = rect.contains(x, y);
擴(kuò)展
1. 在 Activity 的 onCreate() 方法中由于控件尚未繪制完成抱虐,獲取不到控件的高度颈将、位置,可以在 Activity 的 onWindowFocusChanged() 方法中獲妊粤啤:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
RectF rect = calcViewScreenLocation(viewMotion); // 獲取控件的坐標(biāo)
}
}
2. 可以使用 RectF.contains(RectF)晴圾、RectF.contains(float, float, float, float) 判斷一個矩形是否包含在另一個矩形中:
// RectF source;
// RectF target;
// 判斷 target 矩形是否包含在 source 矩形中
boolean isTargetInSource = source.contains(target);
boolean isTargetInSource = source.contains(target.left, target.top,
target.right, target.bottom);