问题描述,需求是子viewpager滑动到极限之后使父viewpager进行滑动,目前的问题是子viewpager滑动到极限之后父viewpager无法滑动
解决方法是在父类中进行拦截,当子view是viewpager时进行判断处理不让子view滑动
public class GalleryViewPager extends ViewPager {
private static final String TAG = GalleryViewPager.class.getSimpleName();
public GalleryViewPager(Context context) {
super(context);
}
public GalleryViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
// 请求父容器不要拦截本控件的事件
getParent().requestDisallowInterceptTouchEvent(true);
return super.dispatchTouchEvent(ev);
}
@Override
protected boolean canScroll(View v, boolean checkV, int dx, int x, int y) {
if (v instanceof ViewPager) {
Log.i(TAG, "canScroll: ");
// Let the child ViewPager handle its own scrolling first.
ViewPager childViewPager = (ViewPager) v;
int childCount = childViewPager.getChildCount();
int childWidth = 0;
for (int i = 0; i < childCount; i++) {
View child = childViewPager.getChildAt(i);
childWidth += child.getWidth();
}
int scrollX = childViewPager.getScrollX();
Log.i(TAG, "canScroll: " + scrollX);
if (dx < 0) {
Log.i(TAG, "canScroll: dx<0");
// Paging left.
if (scrollX > 0) {
// Already at the left edge.
return true;
}
} else if (dx > 0) {
Log.i(TAG, "canScroll: dx>0");
// Paging right.
if (scrollX < childWidth - getWidth()) {
Log.i(TAG, "canScroll: dx>0 111");
// Not at the right edge.
return false;
}
}
}
return super.canScroll(v, checkV, dx, x, y);
}
}