如何检测任何子视图何时获得点击 [英] How to detect when any child view recieves a click

查看:81
本文介绍了如何检测任何子视图何时获得点击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定具有任意子视图集合的任意ViewGroup G,如何检测用户单击任何子视图的时间?在这种情况下,我要为G绘制一个亮点.

Given an arbitrary ViewGroup G with an arbitrary collection of child views, how can I detect when the user clicks on any of the child views? In this case, I want to draw a highlight for G.

我可以为每个孩子添加一个onClick侦听器,但是我试图避免这种情况,以便在布局更改时不必更改代码.

I could add an onClick listener for each child, but I'm trying to avoid that so that the code doesn't have to be changed when the layouts change.

或者,我可以将onTouch处理程序添加到G并在ACTION_DOWN期间设置突出显示.但是,这会触发实际上并不会导致点击的操作,例如滑动(例如,滑动可以由ViewPager处理,最终与G无关).

Alternatively, I could add onTouch handlers to G and set the highlight during ACTION_DOWN. However, this would trigger for actions that don't actually result in clicks, such as a swipe (the swipe could be handled by ViewPager, for example, and ultimately be irrelevant to G).

我的G布局具有可聚焦的属性:

My layout for G has the focusable attributes:

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...

现在,您可以将父级定位为在其内部完成的所有点击的代表,即使它是在子级中完成的.

Now, you can target the parent as the delegate of all clicks done inside it, even if it is done in a child.

要忽略其他非点击事件,您可以询问用户手指移动了多少:

To ignore other touch event that are not click, you can ask for how much user moved the finger:

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像素的正方形以允许舒适的点击,如果退出它,我会忽略它.

I give a square of 10 pixels to permit a confortable click, and if you exit it, I ignore it.

额外:

这是完整的代码,用于通过onTouchListener进行点击和长按.

Here is the complete code for click and long click with onTouchListener.

这篇关于如何检测任何子视图何时获得点击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆