美文网首页自定义view相关Android程序猿View
Android自定义垂直方向的ViewPager

Android自定义垂直方向的ViewPager

作者: iflymoon | 来源:发表于2016-07-19 10:39 被阅读2544次

    由于项目需要,做了一个垂直滑动的ViewPager作为应用的引导页,下面就和大家分享一下具体实现方法,初步测试可以使用,先看效果图:



    废话不多说,下面来看一看代码,由于代码中已经写了很多注释,我就不过多解释了,大概思路就是自定义一个类继承自ViewGroup,然后将视图集合放进去,下面是实现类VerticalViewPager.java:

    public class VerticalViewPager extends ViewGroup {   
      // 用于滑动的类   
      private Scroller scroller;   
      // 用来跟踪触摸速度的类   
      private VelocityTracker velocityTracker;   
      // 当前的屏幕视图   
      private int curScreen;   
      // 默认的显示视图   
      private int defaultScreen = 0;   
      // 无事件的状态   
      private static final int TOUCH_STATE_REST = 0;   
      // 处于拖动的状态   
      private static final int TOUCH_STATE_SCROLLING = 1;   
      // 可以切换页面的最小滑动的速度   
      private static final int SNAP_VELOCITY = 500;   
      // 所处的状态   
      private int touchState = TOUCH_STATE_REST;   
      private int touchSlop;   
      private float lastMotionY;   
      private OnVerticalPageChangeListener verticalPageChangeListener;   
      public VerticalViewPager(Context context) {      
        this(context, null);   
      }   
      public VerticalViewPager(Context context, AttributeSet attrs) {      
        this(context, attrs, 0);   
      }   
      /**    
        * 在构造器中进行一些初始化    
        */   
      public VerticalViewPager(Context context, AttributeSet attrs, int defStyle) {      
        super(context, attrs, defStyle);      
        scroller = new Scroller(context);      
        curScreen = defaultScreen;      
        // ViewConfiguration.get(getContext()).getScaledTouchSlop()可以得到一个距离,ViewPager就是用这个距离来判断用户是否翻页      
        touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop()/4;   
      }   
      public interface OnVerticalPageChangeListener {      
        public void onVerticalPageSelected(int position);   
      }   
      /**    
        * 提供一个页面改变的监听器    
        */   
      public void setOnVerticalPageChangeListener(OnVerticalPageChangeListener onVerticalPageChangeListener) {      
        this.verticalPageChangeListener = onVerticalPageChangeListener;   
      }   
      public void setViewList(List<View> viewList) {      
        for (int i = 0; i < viewList.size(); i++) {         
          this.addView(viewList.get(i));      
        }      
        invalidate();   
      }   
      /**    
        * 重写此方法为子View进行布局    
        */   
      @Override   
      protected void onLayout(boolean changed, int l, int t, int r, int b) {      
        int childheiht = 0;      
        for (int i = 0; i < getChildCount(); i++) {         
          View childView = getChildAt(i);         
          if (childView.getVisibility() != View.GONE) {            
            int childWidth = childView.getMeasuredWidth();            
            childView.layout(0, childheiht, childWidth, childView.getMeasuredHeight() + childheiht);
            childheiht += childView.getMeasuredHeight();         
          }      
        }   
      }   
      /**    
        * 重写此方法用来计算高度和宽度    
        */   
      @Override   
      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec{
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);      
        // 得到多少页(子View)并设置他们的宽和高      
        for (int i = 0; i < getChildCount(); i++) {         
          getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);      
        }   
      }   
      /**    
        * 根据目前的位置滚动到下一个视图位置    
        */   
      public void snapToDestination() {      
        int screenHeight = getHeight();      
        // 根据View的高度以及滑动的值来判断是哪个View      
        int destScreen = (getScrollY() + screenHeight/2) / screenHeight;      
        snapToScreen(destScreen);   
      }   
      public void snapToScreen(int whichScreen) {      
        whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));      
        if (getScrollY() != (whichScreen * getHeight())) {         
          final int delta = whichScreen * getHeight() - getScrollY();         
          scroller.startScroll(0, getScrollY(), 0, delta, Math.abs(delta)/4);         
          curScreen = whichScreen;         
          invalidate(); 
          // 重新布局         
          if (verticalPageChangeListener != null)
            verticalPageChangeListener.onVerticalPageSelected(whichScreen);      
        }   
      }   
      public void setToScreen(int whichScreen) {      
        whichScreen = Math.max(0, Math.min(whichScreen, getChildCount() - 1));      
        curScreen = whichScreen;      
        scrollTo(0, whichScreen * getHeight());      
        if (verticalPageChangeListener != null)
          verticalPageChangeListener.onVerticalPageSelected(whichScreen);   
      }   
      /**    
        * 获取当前页面    
        * @return 当前页面值    
        */   
      public int getCurScreen() {      
        return curScreen;   
      }   
      /**    
        * 获取当前视图    
        * @return 当前视图    
        */   
      public View getCurrentView() {      
        return getChildAt(getCurScreen());   
      }   
      /**    
        * 根据位置获取指定页面的视图    
        * @param position 页面位置    
        * @return 指定页面的视图    
        */   
      public View getView(int position) {      
        return getChildAt(position);   
      }   
      @Override   
      public void computeScroll() {      
        if (scroller.computeScrollOffset()) {         
          scrollTo(scroller.getCurrX(), scroller.getCurrY());         
          postInvalidate();      
        }   
      }   
      public boolean onTouchEvent(MotionEvent event) {      
        if (velocityTracker == null) {         
          // 使用obtain方法得到VelocityTracker的一个对象         
          velocityTracker = VelocityTracker.obtain();      
        }      
        // 将当前的触摸事件传递给VelocityTracker对象      
        velocityTracker.addMovement(event);      
        // 得到触摸事件的类型      
        final int action = event.getAction();      
        final float y = event.getY();      
        switch (action) {         
          case MotionEvent.ACTION_DOWN:            
            if (!scroller.isFinished()) {               
              scroller.abortAnimation();            
            }            
            lastMotionY = y;            
            break;         
          case MotionEvent.ACTION_MOVE:            
            int deltay = (int) (lastMotionY - y);            
            lastMotionY = y;            
            scrollBy(0, deltay);            
            break;         
          case MotionEvent.ACTION_UP:            
            final VelocityTracker velocityTracker = this.velocityTracker;            
            // 计算当前的速度            
            velocityTracker.computeCurrentVelocity(1000);            
            // 获得Y轴方向当前的速度            
            int velocityY = (int) velocityTracker.getYVelocity();            
            if (velocityY > SNAP_VELOCITY && curScreen > 0) {               
              snapToScreen(curScreen - 1);            
            } else if (velocityY < -SNAP_VELOCITY && curScreen < getChildCount() - 1) {
              snapToScreen(curScreen + 1);            
            } else {               
              snapToDestination();            
            }            
            if (this.velocityTracker != null) {               
              this.velocityTracker.recycle();               
              this.velocityTracker = null;            
            }            
            touchState = TOUCH_STATE_REST;            
            break;         
          case MotionEvent.ACTION_CANCEL:            
            touchState = TOUCH_STATE_REST;            
            break;      
        }      
        return true;   
      }   
      @Override   
      public boolean onInterceptTouchEvent(MotionEvent ev) {      
        final int action = ev.getAction();      
        if ((action == MotionEvent.ACTION_MOVE) && (touchState != TOUCH_STATE_REST)) {
          return true;      
        }      
        final float y = ev.getY();      
        switch (action) {         
          case MotionEvent.ACTION_MOVE:            
            final int xDiff = (int) Math.abs(lastMotionY - y);            
            if (xDiff > touchSlop) {               
              touchState = TOUCH_STATE_SCROLLING;            
            }            
            break;         
          case MotionEvent.ACTION_DOWN:            
            lastMotionY = y;            
            touchState = scroller.isFinished() ? TOUCH_STATE_REST                  : TOUCH_STATE_SCROLLING;            
            break;         
          case MotionEvent.ACTION_CANCEL:         
          case MotionEvent.ACTION_UP:            
            touchState = TOUCH_STATE_REST;            
            break;      
        }      
        return touchState != TOUCH_STATE_REST;   
      }
    }
    

    其实这个并不难,都是一些基础的东西,但是要理解ViewGroup的onMeasure和onLayout方法,这样才能对自定义的这个控件中的子View进行位置排布。下面就是这个自定义控件的用法了,首先是布局文件activity_main.xml:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"    
      android:layout_height="match_parent">    
      <me.my.verticalviewpager.VerticalViewPager        
        android:layout_width="fill_parent"        
        android:layout_height="fill_parent"        
        android:id="@+id/vertical_viewpager"/>
    </RelativeLayout>
    

    之后就是在代码中使用了,文件MainActivity.java:

    public class MainActivity extends Activity {    
      private VerticalViewPager verticalViewPager;    
      private final int[] imgSource = { R.drawable.bg_android_v7_1, R.drawable.bg_android_v7_2, R.drawable.bg_android_v7_3, R.drawable.bg_android_v7_4, R.drawable.bg_android_v7_5, R.drawable.bg_android_v7_6};    
      @Override    
      protected void onCreate(Bundle savedInstanceState) {        
        super.onCreate(savedInstanceState);        
        setContentView(R.layout.activity_main);        
        verticalViewPager = (VerticalViewPager) findViewById(R.id.vertical_viewpager);        
        List<View> viewList = new ArrayList<View>();        
        for (int i = 0; i < imgSource.length; i++) {            
          View view = getLayoutInflater().inflate(R.layout.pager, null);            
          ImageView img = (ImageView) view.findViewById(R.id.pager);
          img.setImageResource(imgSource[i]);            
          viewList.add(view);        
        }        
        verticalViewPager.setViewList(viewList);    
      }
    }
    

    上面用到了一些图片,还有一个布局文件pager.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="match_parent"    
      android:layout_height="match_parent"    
      android:orientation="vertical" >        
      <ImageView         
        android:layout_width="fill_parent"        
        android:layout_height="fill_parent"        
        android:scaleType="fitXY"        
        android:id="@+id/pager"/>    
    </LinearLayout>
    

    好了,到这里就介绍完了,具体demo我放在了这里http://download.csdn.net/detail/flymoon1201/8554741
    欢迎大家指正批评哈!

    相关文章

      网友评论

      • 落雁沙世界:怎么让第一页不再网下滑动,第二页不再往上滑动;让滑动有边界和区间
      • 捡淑:mark
        _郭霖:哪里都能遇到你:joy:
      • panda_Vicky:理论上监听recyclerview的scrolllistener能实现同样的效果
      • panda_Vicky:没有重用啊

      本文标题:Android自定义垂直方向的ViewPager

      本文链接:https://www.haomeiwen.com/subject/tqnpjttx.html