最近项目中使用了fragment,如图:,上半部分是一个自定义的ViewGroup,可以左右滑动,使用了Viewpager。现在麻烦就来了,两个控件都是要左右滑动的,但是现在无法解决两者左右滑动事件的分发。在stackoverflow上面看到一个帖子:
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE:
pager.requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
pager.requestDisallowInterceptTouchEvent(false);
break;
}
}
ViewPager对外提供一个这样的方法requestDisallowInterceptTouchEvent();
于是我在自定义的ViewGroup的onTouchEvent()也用了这个方法,解决了这个问题:
具体代码:
@Override
public boolean onTouchEvent(MotionEvent event) {
v.requestDisallowInterceptTouchEvent(true);
gestureDetector.onTouchEvent(event);
if(event.getAction() == MotionEvent.ACTION_UP){
handler.removeCallbacks(next);
if(time>=500)
handler.postDelayed(next, time);
if(!fling){
// 当用户停止拖动
snapToDestination();
v.requestDisallowInterceptTouchEvent(false);
}
fling = false;
}
if(event.getAction() == MotionEvent.ACTION_CANCEL){
v.requestDisallowInterceptTouchEvent(false);
}
return true;
}