TextView选中文本弹出菜单点击外部区域无法自动关闭如何解决?
实现方案
方案1:重写Activity的dispatchTouchEvent(全局适配,侵入性低)
仅需在触摸事件分发阶段判断点击区域是否落在已选中文本的TextView范围内,若不在则主动清除文本选中状态即可关闭操作菜单,不会影响原有交互逻辑,无需为页面内其他控件单独设置监听。
Kotlin 实现代码
override fun dispatchTouchEvent(ev: MotionEvent): Boolean { if (ev.action == MotionEvent.ACTION_DOWN) { // 获取当前持有焦点的View,通常为选中了文本的可选择TextView val focusedView = currentFocus if (focusedView is TextView && focusedView.textIsSelectable && focusedView.hasSelection()) { // 计算TextView在屏幕中的坐标范围 val location = IntArray(2) focusedView.getLocationOnScreen(location) val x = ev.rawX val y = ev.rawY // 判断点击是否落在TextView外部 val isTouchOutside = x < location[0] || x > location[0] + focusedView.width || y < location[1] || y > location[1] + focusedView.height if (isTouchOutside) { // 清除选中状态,自动关闭操作菜单 focusedView.clearSelection() } } } return super.dispatchTouchEvent(ev) }
Java 实现代码
@Override public boolean dispatchTouchEvent(MotionEvent ev) { if (ev.getAction() == MotionEvent.ACTION_DOWN) { View focusedView = getCurrentFocus(); if (focusedView instanceof TextView) { TextView selectableTv = (TextView) focusedView; if (selectableTv.isTextSelectable() && selectableTv.hasSelection()) { int[] location = new int[2]; selectableTv.getLocationOnScreen(location); float x = ev.getRawX(); float y = ev.getRawY(); boolean isTouchOutside = x < location[0] || x > location[0] + selectableTv.getWidth() || y < location[1] || y > location[1] + selectableTv.getHeight(); if (isTouchOutside) { selectableTv.clearSelection(); } } } } return super.dispatchTouchEvent(ev); }
方案2:给根布局设置触摸监听器(单页面适配,无需修改Activity)
如果不需要全局适配,仅想在单个页面实现该效果,可以直接给当前页面的根View添加触摸监听器,判断逻辑和上述方案完全一致:
// 在onCreate/onViewCreated中给根布局设置监听 rootView.setOnTouchListener { _, event -> if (event.action == MotionEvent.ACTION_DOWN) { val focusedView = currentFocus if (focusedView is TextView && focusedView.textIsSelectable && focusedView.hasSelection()) { val location = IntArray(2) focusedView.getLocationOnScreen(location) val isTouchOutside = event.rawX < location[0] || event.rawX > location[0] + focusedView.width || event.rawY < location[1] || event.rawY > location[1] + focusedView.height if (isTouchOutside) { focusedView.clearSelection() } } } // 返回false不拦截原有触摸事件,不影响其他控件的交互逻辑 false }
以上两种方案均无需处理软键盘逻辑,也不需要为除TextView外的所有视图单独添加监听器,完全适配可选择TextView的使用场景,不会影响页面原有交互逻辑。
内容的提问来源于stack exchange,提问作者Damn Vegetables
相关产品推荐
相关产品推荐

