Android ViewPager与SwipeBackLayout的业务需求解决

笔者在登陆页面使用了ViewPager与SwipeBackLayout,但有一个业务需求是:

ViewPager在第二页是可以右滑到第一页,当ViewPager在第一页时,才会触发SwipeBackLayout的右滑返回,ViewPager在第一页可以左滑到ViewPager的第二页。

参考了ViewPager的源码,做出以下解决办法:

继承ViewPager类,重写dispatchTouchEvent方法。二话不说,上代码:

package com.dalinbobo.lapa.palette.customviewpager;

import android.content.Context;
import android.support.v4.view.ViewConfigurationCompat;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.ViewConfiguration;

/** * 用于解决滑动冲突的登陆用的viewpager * Created by qin on 2016/3/23. */
public class LoginViewPager extends ViewPager {

    private int mTouchSlop;

    public LoginViewPager(Context context) {
        super(context);
        init();
    }

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

    private void init() {
        final Context context = getContext();
        final ViewConfiguration configuration = ViewConfiguration.get(context);
        mTouchSlop = ViewConfigurationCompat.getScaledPagingTouchSlop(configuration);
    }

    float mLastX;
    float mLastY;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (getCurrentItem() == 0) {
            float x = ev.getX();
            float y = ev.getY();
            switch (ev.getAction()) {
                case MotionEvent.ACTION_MOVE:
                    float xDiff = Math.abs(x - mLastY);
                    float yDiff = Math.abs(y - mLastY);
                    //在第一页,判断到是向左边滑动,即想滑动第二页
                    if (xDiff > 0 && x - mLastX < 0 && xDiff * 0.5f > yDiff) {
                        //告诉父容器不要拦截事件
                        getParent().requestDisallowInterceptTouchEvent(true);
                    }else if (yDiff > mTouchSlop && xDiff < mTouchSlop) {
                        //竖直滑动时,告诉父容器拦截事件,用于在ScrollView中可以竖直滑动
                        getParent().requestDisallowInterceptTouchEvent(false);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    getParent().requestDisallowInterceptTouchEvent(false);
                    break;
            }
            mLastX = x;
            mLastY = y;
        } else {
            getParent().requestDisallowInterceptTouchEvent(true);
        }
        return super.dispatchTouchEvent(ev);
    }
}

来自:
http://blog.csdn.net/u013003052/article/details/50964968

你可能感兴趣的:(viewpager)