Android开发如何获取屏幕选中区域内的所有View并实现矩形高亮
实现Android指定区域内View高亮的方案
1. 捕获用户选中的区域
首先给你需要监听的顶层布局(通常是根布局/DecorView)设置触摸监听,记录按下和抬起的坐标生成选中区域矩形对象:
- 示例代码:
var selectRect = Rect() var downX = 0f var downY = 0f // rootView可替换为你要监听的顶层View rootView.setOnTouchListener { v, event -> when(event.action) { MotionEvent.ACTION_DOWN -> { downX = event.rawX downY = event.rawY // 每次按下先清除之前的高亮 clearAllHighlight() } MotionEvent.ACTION_UP -> { val upX = event.rawX val upY = event.rawY selectRect.apply { left = min(downX, upX).toInt() top = min(downY, upY).toInt() right = max(downX, upX).toInt() bottom = max(downY, upY).toInt() } // 遍历查找区域内的View findViewsInRect(selectRect, rootView as ViewGroup) } } true }
2. 遍历View树匹配区域内的可见View
递归遍历所有子View,过滤不可见的View,判断View的屏幕坐标是否和选中区域匹配:
- 示例代码:
private fun findViewsInRect(targetRect: Rect, parent: ViewGroup) { for (i in 0 until parent.childCount) { val child = parent.getChildAt(i) // 跳过不可见的View if (child.visibility != View.VISIBLE) continue // 获取View在全局屏幕的坐标 val childLocation = IntArray(2) child.getLocationOnScreen(childLocation) val childRect = Rect( childLocation[0], childLocation[1], childLocation[0] + child.width, childLocation[1] + child.height ) // 判断两个矩形是否相交,如需完全包含在选区内可替换为targetRect.contains(childRect) if (Rect.intersects(targetRect, childRect)) { addHighlightToView(child) } // 如果是容器布局继续递归遍历子View if (child is ViewGroup) { findViewsInRect(targetRect, child) } } }
3. 给匹配View添加高亮效果
这里用View的foreground属性实现描边+半透明背景的高亮效果,兼容API 23+,低版本可替换为添加覆盖层的方案:
- 提前在
res/values/ids.xml定义tag id避免冲突:
<resources> <item name="tag_original_foreground" type="id"/> </resources>
- 高亮逻辑代码:
private fun addHighlightToView(view: View) { // 自定义高亮样式,可自行修改颜色、描边粗细、圆角 val highlightDrawable = GradientDrawable().apply { shape = GradientDrawable.RECTANGLE setStroke(4.dpToPx(), Color.RED) setColor(Color.parseColor("#33FF0000")) // 自动适配原View的圆角 cornerRadius = if (view.background is GradientDrawable) { (view.background as GradientDrawable).cornerRadius } else 0f } // 保存原始foreground,清除高亮时恢复 view.setTag(R.id.tag_original_foreground, view.foreground) view.foreground = highlightDrawable } // dp转px扩展方法 fun Int.dpToPx(): Int = (this * Resources.getSystem().displayMetrics.density).toInt()
4. 清除高亮的方法
private fun clearAllHighlight(parent: ViewGroup? = null) { val root = parent ?: (window.decorView as ViewGroup) for (i in 0 until root.childCount) { val child = root.getChildAt(i) val originalForeground = child.getTag(R.id.tag_original_foreground) as? Drawable if (originalForeground != null) { child.foreground = originalForeground child.setTag(R.id.tag_original_foreground, null) } if (child is ViewGroup) { clearAllHighlight(child) } } }
如需兼容API 23以下系统,可替换实现逻辑:给匹配到的View的父布局添加一层同等位置的半透明描边覆盖View,遍历逻辑和上述一致。
内容的提问来源于stack exchange,提问作者Nguyen Cuong
相关产品推荐
相关产品推荐

