Android 根据坐标获取控件方法

/**
	 * 根据坐标获取相对应的子控件<br>
	 * 在Activity使用
	 * 
	 * @param x坐标
	 * @param y坐标
	 * @return 目标View
	 */
	public View getViewAtActivity(int x, int y) {
		// 从Activity里获取容器
		View root = getWindow().getDecorView();
		return findViewByXY(root, x, y);
	}

	/**
	 * 根据坐标获取相对应的子控件<br>
	 * 在重写ViewGroup使用
	 * 
	 * @param x坐标
	 * @param y坐标
	 * @return 目标View
	 */
	public View getViewAtViewGroup(int x, int y) {
		return findViewByXY(this, x, y);
	}

	private View findViewByXY(View view, int x, int y) {
		View targetView = null;
		if (view instanceof ViewGroup) {
			// 父容器,遍历子控件
			ViewGroup v = (ViewGroup) view;
			for (int i = 0; i < v.getChildCount(); i++) {
				targetView = findViewByXY(v.getChildAt(i), x, y);
				if (targetView != null) {
					break;
				}
			}
		} else {
			targetView = getTouchTarget(view, x, y);
		}
		return targetView;

	}

	private View getTouchTarget(View view, int x, int y) {
		View targetView = null;
		// 判断view是否可以聚焦
		ArrayList<View> TouchableViews = view.getTouchables();
		for (View child : TouchableViews) {
			if (isTouchPointInView(child, x, y)) {
				targetView = child;
				break;
			}
		}
		return targetView;
	}

	private boolean isTouchPointInView(View view, int x, int y) {
		int[] location = new int[2];
		view.getLocationOnScreen(location);
		int left = location[0];
		int top = location[1];
		int right = left + view.getMeasuredWidth();
		int bottom = top + view.getMeasuredHeight();
		if (view.isClickable() && y >= top && y <= bottom && x >= left
				&& x <= right) {
			return true;
		}
		return false;
	}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值