Android ViewPager嵌套ViewPager联动简单实现

ViewPager嵌套联动效果.gif

代码:

/**
 * ================================
 * Des: 联动滑动 ViewPager
 * Created by kele on 2021/2/23.
 * E-mail:[email protected]
 * ================================
 */
public class LinkageSlidingViewPager extends ViewPager {

    public LinkageSlidingViewPager(Context context) {
        this(context, null);
    }

    public LinkageSlidingViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                getParent().requestDisallowInterceptTouchEvent(true);
                break;
            case MotionEvent.ACTION_MOVE:
                int curPosition = this.getCurrentItem();
                int count = this.getAdapter().getCount();
                // 当当前页面在最后一页和第0页的时候,由父亲拦截触摸事件
                if (curPosition == count - 1 || curPosition == 0) {
                    getParent().requestDisallowInterceptTouchEvent(false);
                } else {//其他情况,由孩子拦截触摸事件
                    getParent().requestDisallowInterceptTouchEvent(true);
                }
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
}

参考链接:

https://blog.csdn.net/gdutxiaoxu/article/details/52939127

你可能感兴趣的:(Android ViewPager嵌套ViewPager联动简单实现)