最近在做一个项目需要用到ViewPager加载广告图,布局中需要侧滑,用了android V4包里的SlidingPaneLayout控件(该控件在旧的v4包里面没有,需要更新v4包),项目中使用的时候,发现在滑动中ViewPager和SlidingPaneLayout滑动冲突了,当手指从左向右滑动时,ViewPager的滑动事件被SlidingPaneLayout屏蔽了,只能执行SlidingPaneLayout的事件,而从右往左滑时,则正常。
国内找了一些资料,发现不是特别好,最后还是靠VPNFQ去国外论坛找(果然是世界最大的局域网),这个问题在国外论坛上一下子就找到了(不得不说国外的资源就是丰富,给外国友人点个赞)所以下面的处理代码,是转载国外的,可以直接复制使用,暂时没发现问题,有问题以后再修改。
这里说一下处理步骤,自己新建一个类,继承于SlidingPaneLayout,然后把这个类添加到你所要布局的XML文件里,这样就可以了。下面贴代码。
package com.zuzuChe.view; import android.content.Context; import android.support.v4.view.MotionEventCompat; import android.support.v4.widget.SlidingPaneLayout; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.ViewConfiguration; /** * Created by apaojun on 2015/2/12. */ public class PagerEnabledSlidingPaneLayout extends SlidingPaneLayout { private float mInitialMotionX; private float mInitialMotionY; private float mEdgeSlop; public PagerEnabledSlidingPaneLayout(Context context) { this(context, null); } public PagerEnabledSlidingPaneLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PagerEnabledSlidingPaneLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); ViewConfiguration config = ViewConfiguration.get(context); mEdgeSlop = config.getScaledEdgeSlop(); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { switch (MotionEventCompat.getActionMasked(ev)) { case MotionEvent.ACTION_DOWN: { mInitialMotionX = ev.getX(); mInitialMotionY = ev.getY(); break; } case MotionEvent.ACTION_MOVE: { final float x = ev.getX(); final float y = ev.getY(); // The user should always be able to "close" the pane, so we only check // for child scrollability if the pane is currently closed. if (mInitialMotionX > mEdgeSlop && !isOpen() && canScroll(this, false, Math.round(x - mInitialMotionX), Math.round(x), Math.round(y))) { // How do we set super.mIsUnableToDrag = true? // send the parent a cancel event MotionEvent cancelEvent = MotionEvent.obtain(ev); cancelEvent.setAction(MotionEvent.ACTION_CANCEL); return super.onInterceptTouchEvent(cancelEvent); } } } return super.onInterceptTouchEvent(ev); } }