自定义ViewPager

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.administrator.viewpager.MainActivity">

    <com.example.administrator.viewpager.MyViewPager
        android:id="@+id/my_viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</RelativeLayout>


package com.example.administrator.viewpager;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private MyViewPager viewPager;
    private int[] datas;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initDatas();
        initEvent();
    }

    private void initView() {
        viewPager = (MyViewPager) findViewById(R.id.my_viewpager);
    }

    private void initDatas() {
        datas = new int[]{R.drawable.image01, R.drawable.image02, R.drawable.image03, R.drawable.image04};
        for (int i = 0; i < datas.length; i++) {
            ImageView iv = new ImageView(MainActivity.this);
            iv.setBackgroundResource(datas[i]);
            viewPager.addView(iv);
        }
    }

    private void initEvent() {
    }
}


package com.example.administrator.viewpager;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

/**
 * Created by Administrator on 2017/5/16.
 */

public class MyViewPager extends ViewGroup {
    private static final String TAG = "TAG";
    private GestureDetector mDetector;
    private float startX;
    private int currentIndex;
    private MyScroll myScroll;

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

    private void initView(Context context) {
        myScroll = new MyScroll();
        mDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public void onLongPress(MotionEvent e) {
                super.onLongPress(e);
                Log.e(TAG, "长按");
            }

            /**
             *
             * @param e1:开始点击的
             * @param e2:接受位置的
             * @param distanceX
             * @param distanceY
             * @return
             */
            @Override
            public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
                if (currentIndex == 0 && e2.getX() > e1.getX()) {
                    scrollBy(0, 0);
                } else if (currentIndex == getChildCount() - 1 && e2.getX() < e1.getX()) {
                    scrollBy(0, 0);
                } else {

                    scrollBy((int) distanceX, 0);
                }
                return true;
            }

            @Override
            public boolean onDoubleTapEvent(MotionEvent e) {
                Log.e(TAG, "双击");
                return super.onDoubleTapEvent(e);
            }
        });
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        for (int i = 0; i < getChildCount(); i++) {
            View view = getChildAt(i);
            view.layout(i * getWidth(), 0, (i + 1) * getWidth(), getHeight());
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        super.onTouchEvent(event);
        mDetector.onTouchEvent(event);
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = event.getX();
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                float endX = event.getX();
                int index = currentIndex;
                if ((startX - endX) > getWidth() / 2) {//从右→左滑动
                    index++;
                } else if ((endX - startX) > getWidth() / 2) {//从左←右滑动
                    index--;
                }
                scrollToPager(index);
                break;
        }
        return true;
    }

    /**
     * 屏蔽非法值,根据位置移动到指定页面
     *
     * @param index
     */
    private void scrollToPager(int index) {
        if (index > getChildCount() - 1) {
            index = getChildCount() - 1;
        }
        if (index < 0) {
            index = 0;
        }
        currentIndex = index;
//        scrollTo(currentIndex * getWidth(), 0);

        myScroll.startScroll(getScrollX(), getScrollY(), currentIndex * getWidth() - getScrollX(), 0);
        invalidate();//执行后会调用Draw(),computeScroll();
    }

    @Override
    public void computeScroll() {
        if (myScroll.computeScrollOffset()) {
            scrollTo((int) myScroll.getCurrX(), 0);
            invalidate();
        }
    }
}
package com.example.administrator.viewpager;

import android.os.SystemClock;

/**
 * Created by Administrator on 2017/5/16.
 */

public class MyScroll {
    /**
     * X轴起始坐标
     */
    private float startScrollX;
    /**
     * Y轴起始坐标
     */
    private float startScrollY;
    /**
     * X轴要滑动的距离
     */
    private int distanceX;
    /**
     * Y轴要滑动的距离
     */
    private int distanceY;
    /**
     * 开机时间
     */
    private long startTime;
    /**
     * 是否滑动结束
     * true:滑动结束
     * false:未结束
     */
    private boolean isFinish;
    /**
     * 总时间
     */
    private long totalTime = 300;
    private float currX;

    /**
     * @param startScrollX:开始位置的X
     * @param startScrollY:开始位置的Y
     * @param distanceX:X轴要滑动的距离
     * @param distanceY:Y轴要滑动的距离
     */
    public void startScroll(float startScrollX, float startScrollY, int distanceX, int distanceY) {
        this.startScrollX = startScrollX;
        this.startScrollY = startScrollY;
        this.distanceX = distanceX;
        this.distanceY = distanceY;
        this.startTime = SystemClock.uptimeMillis();//系统开机时间
        this.isFinish = false;
    }

    public float getCurrX() {
        return currX;
    }

    public boolean computeScrollOffset() {
        if (isFinish) {
            return false;
        }
        long endTime = SystemClock.uptimeMillis();
        long passTime = endTime - startTime;
        if (passTime < totalTime) {
            //平均速度
            //移动的距离:注意:不能将平均速度跟时间分开写会出现不良效果
            long s = passTime * distanceX / totalTime;
            currX = startScrollX + s;
        } else {
            isFinish = true;
            currX = startScrollX + distanceX;
        }
        return true;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值