工作中想要实现这么一个效果:
如图中,当child有一个click事件,parent有一个longclick事件,当长按child的时候能够触发parent的longclick。
遇到的问题:
当child设置click事件时,长按child不会触发parent的longclick事件。
解决方案
1.当时我的解决方案是为child设置一个和parent一样的longclick事件,这样能够解决该问题,但是实际应用中,parent不止一个child,会有3个以上的child,那么将要为所有的child设置longclick事件,并且写出的代码不美观。
2.第二种解决方式能否让代码自动识别你的意图,是想要触发parent的longclick还是child的click事件。
接下来说明一下第二种解决方式。
对于android事件的派发机制这里不多说,网上能够找到很多的相关博客。在view的onTouchEvent方法中会看到这么一段代码
public boolean onTouchEvent(MotionEvent event) {
……
if (((viewFlags & CLICKABLE) == CLICKABLE ||
(viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
……
return true;
}
return false;
}
其中的判断语句能够很明显的看出来,不论view设置了click还是longclick事件,该view都会消费该点击事件,否则才会把事件再交由父布局的onTouchEvent。需求中,child消费了click事件,所以parent的longclick自然不会被触发。
这里我给出的解决方案是重写parent的dispatchevent方法,根据判断用户点击时间的长短来判断是否将事件派发给child。
public class MyRelativeLayout extends RelativeLayout {
public final static String TAG = "ClickTestActivity";
Activity mActivity;
int mTouchSlop; //最短滑动距离
public MyRelativeLayout(Context context) {
super(context);
init(context);
}
public MyRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyRelativeLayout(Context context, AttributeSet attrs,