码迷,mamicode.com
首页 > 移动开发 > 详细

Android 根据坐标获取控件方法

时间:2015-01-14 15:39:59      阅读:169      评论:0      收藏:0      [点我收藏+]

标签: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;
	}

Android 根据坐标获取控件方法

标签:android   控件   坐标   

原文地址:http://blog.csdn.net/chenlove1/article/details/42709127

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!