首页 > 代码库 > ViewPager嵌套ViewPager后子ViewPager滑动不正常问题

ViewPager嵌套ViewPager后子ViewPager滑动不正常问题

ViewPager嵌套ViewPager后,滑动事件没法在子ViewPager里面响应。

解决办法是自定义子ViewPager。

以下代码是转载的,经本人测试,可以用!!!

转载地址:http://blog.csdn.net/leewenjin/article/details/21011841

 

 

package com.lwj.app.customview;

 

import android.content.Context;

import android.graphics.PointF;

import android.support.v4.view.ViewPager;

import android.util.AttributeSet;

import android.view.MotionEvent;

 

public class ChildViewPager extends ViewPager{

   

    PointF downP = new PointF();

   

    PointF curP = new PointF();

    OnSingleTouchListener onSingleTouchListener;

 

    public ChildViewPager(Context context, AttributeSet attrs) {

        super(context, attrs);

        // TODO Auto-generated constructor stub

    }

 

    public ChildViewPager(Context context) {

        super(context);

        // TODO Auto-generated constructor stub

    }

 

    @Override

    public boolean onInterceptTouchEvent(MotionEvent arg0) {

        // TODO Auto-generated method stub

        //当拦截触摸事件到达此位置的时候,返回true,

        //说明将onTouch拦截在此控件,进而执行此控件的onTouchEvent

        return true;

    }

 

    @Override

    public boolean onTouchEvent(MotionEvent arg0) {

        // TODO Auto-generated method stub

        //每次进行onTouch事件都记录当前的按下的坐标

        curP.x = arg0.getX();

        curP.y = arg0.getY();

 

        if(arg0.getAction() == MotionEvent.ACTION_DOWN){

            //记录按下时候的坐标

            //切记不可用 downP = curP ,这样在改变curP的时候,downP也会改变

            downP.x = arg0.getX();

            downP.y = arg0.getY();

            //此句代码是为了通知他的父ViewPager现在进行的是本控件的操作,不要对我的操作进行干扰

            getParent().requestDisallowInterceptTouchEvent(true);

        }

 

        if(arg0.getAction() == MotionEvent.ACTION_MOVE){

            //此句代码是为了通知他的父ViewPager现在进行的是本控件的操作,不要对我的操作进行干扰

            getParent().requestDisallowInterceptTouchEvent(true);

        }

 

        if(arg0.getAction() == MotionEvent.ACTION_UP){

            //在up时判断是否按下和松手的坐标为一个点

            //如果是一个点,将执行点击事件,这是我自己写的点击事件,而不是onclick

            if(downP.x==curP.x && downP.y==curP.y){

                onSingleTouch();

                return true;

            }

        }

 

        return super.onTouchEvent(arg0);

    }

 

       

    public void onSingleTouch() {

        if (onSingleTouchListener!= null) {

 

            onSingleTouchListener.onSingleTouch();

        }

    }

 

   

    public interface OnSingleTouchListener {

        public void onSingleTouch();

    }

 

    public void setOnSingleTouchListener(OnSingleTouchListener onSingleTouchListener) {

        this.onSingleTouchListener = onSingleTouchListener;

    }

 

}

ViewPager嵌套ViewPager后子ViewPager滑动不正常问题