给定一个包含任意 subview 集合的任意 ViewGroup G,我如何检测用户何时单击了任何 subview ?在这种情况下,我想为G画一个亮点。
我可以为每个 child 添加一个 onClick 监听器,但我试图避免这种情况,以便在布局更改时不必更改代码。
或者,我可以将 onTouch 处理程序添加到 G 并在 ACTION_DOWN 期间设置突出显示。但是,这会触发实际上不会导致点击的操作,例如滑动(滑动可以由 ViewPager 处理,例如,最终与 G 无关)。
我的 G 布局具有可聚焦属性:
android:focusable="true"
android:focusableInTouchMode="true"
谢谢。
最佳答案
这是我的做法:
//in onTouch method of parent, I get the coordinates of click
int x = ((int) motionEvent.getX());
int y = ((int) motionEvent.getY());
//obtain the clickable arrea of the child as HitRect
Rect clickRect = new Rect();
Rect rect = new Rect();
imageView.getHitRect(rect);
//ask if the area contains the coordinates of the click
if(rect.contains(x, y)){
//do some work like if onClickListener on the child was called.
return false; //you clicked here, don't need to handle other Childs
}
//ask for other childs like before...
现在,您可以将父级定位为在其中完成的所有点击的委托(delegate),即使它是在子级中完成的。
编辑:
要忽略其他非点击的触摸事件,您可以询问用户移动了多少手指:
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_CANCEL:
if (Math.abs(motionEvent.getRawX() - initialTouchX) > 5 || Math.abs(motionEvent.getRawY() - initialTouchY) > 5) {
return true; // user mover finger too much, ignore touch
}
return false; // finger still there waiting for click
我给了一个 10 像素的正方形以允许舒适的点击,如果你退出它,我会忽略它。
额外:
这是 complete code使用 onTouchListener 进行点击和长按。
关于android - 如何检测任何 subview 何时收到点击,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22309814/