android自定义控件的惯性滑动

android自定义控件的惯性滑动,第1张

概述原文链接:https://www.jianshu.com/p/57ce979b23e8原文参考:自定义控件的惯性滑动体验RecyclerView的滑动以及滚动的实现源码一、应用场景在自定义View中,常常会用到滚动,但是出于某些原因不能直接继承ScrollView,这时候就很有必要来看看他们滚动都是怎 原文链接:https://www.jianshu.com/p/57ce979b23e8

原文参考:自定义控件的惯性滑动

体验RecyclerVIEw的滑动以及滚动的实现源码

一、应用场景

在自定义view中,常常会用到滚动,但是出于某些原因不能直接继承ScrollVIEw,这时候就很有必要来看看他们滚动都是怎么实现的了。
本文只关注拖动和惯性滑动的效果实现。以RecyclerVIEw的代码为示例(和ScrollVIEw相比,在滚动上的实现方式一样,在惯性滑动的实现上,用的插值器(Interpolator)不同,下文会讲到),抽出RecyclerVIEw中的手指拖动和手指离开后的惯性滑动的代码。

二、效果展示

继承VIEwGroup,实现RecyclerVIEw的滑动效果,如图:

三、核心效果概述单指拖动多指 *** 作时,以新加入的手指为准进行拖动手指松开时的惯性滑动滑动到边缘时的处理四、效果实现

首先,先在onLayout里面加上20个VIEw用来展示拖动的效果(这一部分和滑动无关,只为效果展示,可跳过),这里给出效果图:

共有20个Item,由于还没加滑动,暂时只能显示前两个Item。

4.1 单指拖动

针对用户 *** 作,这时候自然就要用到ontouchEvent()了,区分开用户的按下,移动,抬起 *** 作。
在这之前需要先定义一个常亮mtouchSlop,当手指移动大于这个常量,便表示手指开始拖动,否则,表示手指仅仅只是按下,这样可以更好的区别出用户的意图。

final VIEwConfiguration vc = VIEwConfiguration.get(context);mtouchSlop = vc.getScaledtouchSlop();

下面放出单指拖动的ontouchEnevt()的代码:

public static final int SCRolL_STATE_IDLE = 0;public static final int SCRolL_STATE_DRAGGING = 1;private int mLasttouchY;    @OverrIDepublic boolean ontouchEvent(MotionEvent event) {    final int action = MotionEventCompat.getActionMasked(event);    switch (action) {        case MotionEvent.ACTION_DOWN: {            mScrollState = SCRolL_STATE_IDLE;            mLasttouchY = (int) (event.getY() + 0.5f);            break;        }        case MotionEvent.ACTION_MOVE: {            int y = (int) (event.getY() + 0.5f);            int dy = mLasttouchY - y;            if (mScrollState != SCRolL_STATE_DRAGGING) {                boolean startScroll = false;                if (Math.abs(dy) > mtouchSlop) {                    if (dy > 0) {                        dy -= mtouchSlop;                    } else {                        dy += mtouchSlop;                    }                    startScroll = true;                }                if (startScroll) {                    mScrollState = SCRolL_STATE_DRAGGING;                }            }            if (mScrollState == SCRolL_STATE_DRAGGING) {                mLasttouchY = y;                scrollBy(0, dy);            }            break;        }        case MotionEvent.ACTION_UP: {            break;        }    }    return true;}

上面的代码和变量都是来自RecyclerVIEw的ontouchEvent方法,当然我剔除了单指拖动以外的部分。稍微解释一下主要的思路:
在用户事件:DOWN -> MOVE -> MOVE -> ... -> MOVE -> UP中,首先在DOWN中记录下按下的位置,在每一个MOVE事件中计算和DOWN之间的位置差,当有一个MOVE的位置差大于最小移动距离(mtouchSlop)时,表示拖动开始,开始位移。之后的MOVE事件也无需再次和mtouchSlop比较,直接进行拖动位移,直到UP事件触发。
这时候就存在一个问题,如图:

存在两个手指时,以第一个手指 *** 作为准,当第一个手指松开时,会跳到第二个手指按下时的位置。

4.2 多指 *** 作

多指滑动时就需要指明,控件到底该听谁的。这里就需要有个约束:

以新加入的手指的滑动为准当有一个手指抬起时,以剩下的手指的滑动为准

要做到上面的约束,就不可避免的需要区分出屏幕上的手指。MotionEvent提供getPointerID()方法,用于返回每一个手指的ID。

先奉上添加了多指 *** 作后的ontouchEvent方法的代码:

private static final int INVALID_POINTER = -1;private int mScrollPointerID = INVALID_POINTER;@OverrIDepublic boolean ontouchEvent(MotionEvent event) {    final int action = MotionEventCompat.getActionMasked(event);    final int actionIndex = MotionEventCompat.getActionIndex(event);    switch (action) {        case MotionEvent.ACTION_DOWN: {            setScrollState(SCRolL_STATE_IDLE);            mScrollPointerID = event.getPointerID(0);            mLasttouchY = (int) (event.getY() + 0.5f);            break;        }        case MotionEventCompat.ACTION_POINTER_DOWN: {            mScrollPointerID = event.getPointerID(actionIndex);            mLasttouchY = (int) (event.getY(actionIndex) + 0.5f);            break;        }        case MotionEvent.ACTION_MOVE: {            final int index = event.findPointerIndex(mScrollPointerID);            if (index < 0) {                Log.e("zhufeng", "Error processing scroll; pointer index for ID " + mScrollPointerID + " not found. DID any MotionEvents get skipped?");                return false;            }            final int y = (int) (event.getY(index) + 0.5f);            int dy = mLasttouchY - y;            if (mScrollState != SCRolL_STATE_DRAGGING) {                boolean startScroll = false;                if (Math.abs(dy) > mtouchSlop) {                    if (dy > 0) {                        dy -= mtouchSlop;                    } else {                        dy += mtouchSlop;                    }                    startScroll = true;                }                if (startScroll) {                    setScrollState(SCRolL_STATE_DRAGGING);                }            }            if (mScrollState == SCRolL_STATE_DRAGGING) {                mLasttouchY = y;                scrollBy(0, dy);            }            break;        }        case MotionEventCompat.ACTION_POINTER_UP: {            if (event.getPointerID(actionIndex) == mScrollPointerID) {                // Pick a new pointer to pick up the slack.                final int newIndex = actionIndex == 0 ? 1 : 0;                mScrollPointerID = event.getPointerID(newIndex);                mLasttouchY = (int) (event.getY(newIndex) + 0.5f);            }            break;        }        case MotionEvent.ACTION_UP: {            break;        }    }    return true;}

添加了一个新的变量mScrollPointerID,用于指定当前移动遵循的是哪一个手指的 *** 作,在有新的手指加入时,设置mScrollPointerID为新的手指。在有手指离开的时候,设置mScrollPointerID为剩下的那个手指。
添加了ACTION_POINTER_DOWN和ACTION_POINTER_UP两个事件,在已有DOWN事件后,新增手指点击便会出发ACTION_POINTER_DOWN事件,ACTION_POINTER_DOWN和ACTION_POINTER_UP类似于DOWN和UP事件,都是成对出现。区别在于,DOWN和UP是第一个手指,ACTION_POINTER_DOWN和ACTION_POINTER_UP,只要有一个新的手指加入,就会触发一次。
核心的就是明确当前实际 *** 作的手指(mScrollPointerID),计算位置信息都使用mScrollPointerID的手指即可保证位移信息的正确性。
也来给出个应有的效果:

4.3 惯性滑动

要做到惯性滑动,我们需要做到:

得到手指抬起时的速度将速度转换成具体的位移

4.3.1 获取速度

首先,关于如何在ACTION_UP中得到速度。VeLocityTrackerCompatgetYVeLocity可以获得指定ID的手指当前Y轴上的速度。向上为负,向下为正。关于VeLocityTrackerCompat和VeLocityTracker的使用,这里直接贴出:

private VeLocityTracker mVeLocityTracker;@OverrIDepublic boolean ontouchEvent(MotionEvent event) {    if (mVeLocityTracker == null) {        mVeLocityTracker = VeLocityTracker.obtain();    }    boolean eventAddedToVeLocityTracker = false;    final MotionEvent vtev = MotionEvent.obtain(event);    ...    case MotionEvent.ACTION_UP: {        mVeLocityTracker.addMovement(vtev);        eventAddedToVeLocityTracker = true;        mVeLocityTracker.computeCurrentVeLocity(1000, mMaxFlingVeLocity);        float yVeLocity = -VeLocityTrackerCompat.getYVeLocity(mVeLocityTracker, mScrollPointerID);        ...    }    if (!eventAddedToVeLocityTracker) {        mVeLocityTracker.addMovement(vtev);    }    vtev.recycle();    ...}

4.3.2 将速度反应到滑动上

重点说一下如何将UP时的速度,反应到控件的滚动上。根据OverScroller的fling方法,我们不去探寻这个方法具体是如何实现的,只需要知道,调用了这个方法之后,便可以不停的去调用getCurrY()方法,询问当前移动到哪儿了,知道这次的滑动停止(computeScrollOffset方法返回false)。
这样我们要做的就是:

在UP的时候获取Y轴上的移动速度判断时候需要惯性滑动需要惯性滑动的时候调用OverScrollerfling方法,进行模拟滑动计算在滑动停止之前不停的询问当前按照计算来说应该滑动到哪儿了去设置控件的位置

需要明确的一个概念,OverScroller方法,只涉及到滑动位置的计算,根据输入的值,计算在什么时间应该滑动到什么位置,具体的控件的移动还是需要调用VIEw的ScrollTo或者ScrollBy方法。

落实到代码中就是:

private class VIEwFlinger implements Runnable {    private int mLastFlingY = 0;    private OverScroller mScroller;    private boolean meatRunOnAnimationRequest = false;    private boolean mReSchedulePostAnimationCallback = false;    public VIEwFlinger() {        mScroller = new OverScroller(getContext(), sQuinticInterpolator);    }    @OverrIDe    public voID run() {        disableRunOnAnimationRequests();        final OverScroller scroller = mScroller;        if (scroller.computeScrollOffset()) {            final int y = scroller.getCurrY();            int dy = y - mLastFlingY;            mLastFlingY = y;            scrollBy(0, dy);            postOnAnimation();        }        enableRunOnAnimationRequests();    }    public voID fling(int veLocityY) {        mLastFlingY = 0;        setScrollState(SCRolL_STATE_SETTliNG);        mScroller.fling(0, 0, 0, veLocityY, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);        postOnAnimation();    }    public voID stop() {        removeCallbacks(this);        mScroller.abortAnimation();    }    private voID disableRunOnAnimationRequests() {        mReSchedulePostAnimationCallback = false;        meatRunOnAnimationRequest = true;    }    private voID enableRunOnAnimationRequests() {        meatRunOnAnimationRequest = false;        if (mReSchedulePostAnimationCallback) {            postOnAnimation();        }    }    voID postOnAnimation() {        if (meatRunOnAnimationRequest) {            mReSchedulePostAnimationCallback = true;        } else {            removeCallbacks(this);            VIEwCompat.postOnAnimation(CustomScrollVIEw.this, this);        }    }}

这里用的是RecyclerVIEw中的惯性滑动的代码,剔除了一些不需要的部分。

public voID fling(int veLocityY)方法可以看到,它是从(0,0)坐标开始的。表示,不管当前的VIEw移动到哪儿了,这里的Scroller计算的是,根据参数传递的速度,如果从(0,0)处开始,应该移动到哪儿了。

还有个VIEwCompat.postOnAnimation(vIEw, runable);这句等同于vIEw.postDelayed(runable, 10);

4.3.3 插值器(Interpolator)

在初始化OverScroller的时候,用到了一个sQuinticInterpolator。具体的定义如下:

//f(x) = (x-1)^5 + 1private static final Interpolator sQuinticInterpolator = new Interpolator() {    @OverrIDe    public float getInterpolation(float t) {        t -= 1.0f;        return t * t * t * t * t + 1.0f;    }};

这里用的是一个自定义的插值器。上面提过一下,RecyclerVIEw和ScrollVIEw在惯性滑动上的一部分区别,RecyclerVIEw用的是这个自定义的插值器,ScrollVIEw用的是默认的Scroller.ViscousFluIDInterpolator

插值器的直观的效果之一就是RecyclerVIEw的惯性滑动。也就是刚开始很快,之后慢慢变慢直到停止的效果。

差值器的主要方法getInterpolation(float t)。参数t为滑行时间的百分比,从0到1。返回值为滑行距离的百分比,可以小于0,可以大于1。

用RecyclerVIEw的插值器来举例。如果说根据手指抬起时的速度,最终需要5秒滑动1000像素。根据上面的sQuinticInterpolator插值器,在滑行了2秒的时候,t的值为2/5=0.4getInterpolation(0.4)=0.92表示已经滑动了0.92*1000=920个像素了。更直观的可以通过插值器在[0,1]上的曲线来表达:

横坐标表示时间,纵坐标表示已经完成了总路程的百分比。如图所示,RecyclerVIEw的插值器形成的效果就是在很短时间内首先完成了大部分的路程。正式我们看到的前期很快,后来很慢的效果。

也附上Scroller.ViscousFluIDInterpolator在[0,1]上的曲线图:

感觉没什么太大的区别。

4.4 边缘处理

滑动到上下两边的时候还是能滑动,不妥,需要进行约束。直接贴一下代码就好:

private voID constrainScrollBy(int dx, int dy) {    Rect vIEwport = new Rect();    getGlobalVisibleRect(vIEwport);    int height = vIEwport.height();    int wIDth = vIEwport.wIDth();    int scrollX = getScrollX();    int scrollY = getScrollY();    //右边界    if (mWIDth - scrollX - dx < wIDth) {        dx = mWIDth - scrollX - wIDth;    }    //左边界    if (-scrollX - dx > 0) {        dx = -scrollX;    }    //下边界    if (mHeight - scrollY - dy < height) {        dy = mHeight - scrollY - height;    }    //上边界    if (scrollY + dy < 0) {        dy = -scrollY;    }    scrollBy(dx, dy);}

将代码中的scrollBy都改成添加约束的constrainScrollBy()即可。

五、 给出自定义view的源码
package com.rajesh.scrolldemo;import androID.content.Context;import androID.graphics.color;import androID.graphics.Rect;import androID.support.v4.vIEw.MotionEventCompat;import androID.support.v4.vIEw.VeLocityTrackerCompat;import androID.support.v4.vIEw.VIEwCompat;import androID.util.AttributeSet;import androID.util.displayMetrics;import androID.util.Log;import androID.vIEw.MotionEvent;import androID.vIEw.VeLocityTracker;import androID.vIEw.VIEwConfiguration;import androID.vIEw.VIEwGroup;import androID.vIEw.animation.Interpolator;import androID.Widget.OverScroller;import androID.Widget.TextVIEw;/** * Created by zhufeng on 2017/7/26. */public class CustomScrollVIEw extends VIEwGroup {    private Context mContext;    private int SCREEN_WIDTH = 0;    private int SCREEN_HEIGHT = 0;    private int mWIDth = 0;    private int mHeight = 0;    private static final int INVALID_POINTER = -1;    public static final int SCRolL_STATE_IDLE = 0;    public static final int SCRolL_STATE_DRAGGING = 1;    public static final int SCRolL_STATE_SETTliNG = 2;    private int mScrollState = SCRolL_STATE_IDLE;    private int mScrollPointerID = INVALID_POINTER;    private VeLocityTracker mVeLocityTracker;    private int mLasttouchY;    private int mtouchSlop;    private int mMinFlingVeLocity;    private int mMaxFlingVeLocity;    private final VIEwFlinger mVIEwFlinger = new VIEwFlinger();    //f(x) = (x-1)^5 + 1    private static final Interpolator sQuinticInterpolator = new Interpolator() {        @OverrIDe        public float getInterpolation(float t) {            t -= 1.0f;            return t * t * t * t * t + 1.0f;        }    };    public CustomScrollVIEw(Context context) {        this(context, null);    }    public CustomScrollVIEw(Context context, AttributeSet attrs) {        this(context, attrs, 0);    }    public CustomScrollVIEw(Context context, AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        init(context);    }    @OverrIDe    protected voID onLayout(boolean changed, int l, int t, int r, int b) {        int top = 0;        for (int i = 0; i < 20; i++) {            int wIDth = SCREEN_WIDTH;            int height = SCREEN_HEIGHT / 2;            int left = 0;            int right = left + wIDth;            int bottom = top + height;            //撑大边界            if (bottom > mHeight) {                mHeight = bottom;            }            if (right > mWIDth) {                mWIDth = right;            }            TextVIEw textVIEw = new TextVIEw(mContext);            if (i % 2 == 0) {                textVIEw.setBackgroundcolor(color.CYAN);            } else {                textVIEw.setBackgroundcolor(color.GREEN);            }            textVIEw.setText("item:" + i);            addVIEw(textVIEw);            textVIEw.layout(left, top, right, bottom);            top += height;            top += 20;        }    }    private voID init(Context context) {        this.mContext = context;        final VIEwConfiguration vc = VIEwConfiguration.get(context);        mtouchSlop = vc.getScaledtouchSlop();        mMinFlingVeLocity = vc.getScaledMinimumFlingVeLocity();        mMaxFlingVeLocity = vc.getScaledMaximumFlingVeLocity();        displayMetrics metric = context.getResources().getdisplayMetrics();        SCREEN_WIDTH = metric.wIDthPixels;        SCREEN_HEIGHT = metric.heightPixels;    }    @OverrIDe    public boolean ontouchEvent(MotionEvent event) {        if (mVeLocityTracker == null) {            mVeLocityTracker = VeLocityTracker.obtain();        }        boolean eventAddedToVeLocityTracker = false;        final int action = MotionEventCompat.getActionMasked(event);        final int actionIndex = MotionEventCompat.getActionIndex(event);        final MotionEvent vtev = MotionEvent.obtain(event);        switch (action) {            case MotionEvent.ACTION_DOWN: {                setScrollState(SCRolL_STATE_IDLE);                mScrollPointerID = event.getPointerID(0);                mLasttouchY = (int) (event.getY() + 0.5f);                break;            }            case MotionEventCompat.ACTION_POINTER_DOWN: {                mScrollPointerID = event.getPointerID(actionIndex);                mLasttouchY = (int) (event.getY(actionIndex) + 0.5f);                break;            }            case MotionEvent.ACTION_MOVE: {                final int index = event.findPointerIndex(mScrollPointerID);                if (index < 0) {                    Log.e("zhufeng", "Error processing scroll; pointer index for ID " + mScrollPointerID + " not found. DID any MotionEvents get skipped?");                    return false;                }                final int y = (int) (event.getY(index) + 0.5f);                int dy = mLasttouchY - y;                if (mScrollState != SCRolL_STATE_DRAGGING) {                    boolean startScroll = false;                    if (Math.abs(dy) > mtouchSlop) {                        if (dy > 0) {                            dy -= mtouchSlop;                        } else {                            dy += mtouchSlop;                        }                        startScroll = true;                    }                    if (startScroll) {                        setScrollState(SCRolL_STATE_DRAGGING);                    }                }                if (mScrollState == SCRolL_STATE_DRAGGING) {                    mLasttouchY = y;                    constrainScrollBy(0, dy);                }                break;            }            case MotionEventCompat.ACTION_POINTER_UP: {                if (event.getPointerID(actionIndex) == mScrollPointerID) {                    // Pick a new pointer to pick up the slack.                    final int newIndex = actionIndex == 0 ? 1 : 0;                    mScrollPointerID = event.getPointerID(newIndex);                    mLasttouchY = (int) (event.getY(newIndex) + 0.5f);                }                break;            }            case MotionEvent.ACTION_UP: {                mVeLocityTracker.addMovement(vtev);                eventAddedToVeLocityTracker = true;                mVeLocityTracker.computeCurrentVeLocity(1000, mMaxFlingVeLocity);                float yVeLocity = -VeLocityTrackerCompat.getYVeLocity(mVeLocityTracker, mScrollPointerID);                Log.i("zhufeng", "速度取值:" + yVeLocity);                if (Math.abs(yVeLocity) < mMinFlingVeLocity) {                    yVeLocity = 0F;                } else {                    yVeLocity = Math.max(-mMaxFlingVeLocity, Math.min(yVeLocity, mMaxFlingVeLocity));                }                if (yVeLocity != 0) {                    mVIEwFlinger.fling((int) yVeLocity);                } else {                    setScrollState(SCRolL_STATE_IDLE);                }                resettouch();                break;            }            case MotionEvent.ACTION_CANCEL: {                resettouch();                break;            }        }        if (!eventAddedToVeLocityTracker) {            mVeLocityTracker.addMovement(vtev);        }        vtev.recycle();        return true;    }    private voID resettouch() {        if (mVeLocityTracker != null) {            mVeLocityTracker.clear();        }    }    private voID setScrollState(int state) {        if (state == mScrollState) {            return;        }        mScrollState = state;        if (state != SCRolL_STATE_SETTliNG) {            mVIEwFlinger.stop();        }    }    private class VIEwFlinger implements Runnable {        private int mLastFlingY = 0;        private OverScroller mScroller;        private boolean meatRunOnAnimationRequest = false;        private boolean mReSchedulePostAnimationCallback = false;        public VIEwFlinger() {            mScroller = new OverScroller(getContext(), sQuinticInterpolator);        }        @OverrIDe        public voID run() {            disableRunOnAnimationRequests();            final OverScroller scroller = mScroller;            if (scroller.computeScrollOffset()) {                final int y = scroller.getCurrY();                int dy = y - mLastFlingY;                mLastFlingY = y;                constrainScrollBy(0, dy);                postOnAnimation();            }            enableRunOnAnimationRequests();        }        public voID fling(int veLocityY) {            mLastFlingY = 0;            setScrollState(SCRolL_STATE_SETTliNG);            mScroller.fling(0, 0, 0, veLocityY, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE);            postOnAnimation();        }        public voID stop() {            removeCallbacks(this);            mScroller.abortAnimation();        }        private voID disableRunOnAnimationRequests() {            mReSchedulePostAnimationCallback = false;            meatRunOnAnimationRequest = true;        }        private voID enableRunOnAnimationRequests() {            meatRunOnAnimationRequest = false;            if (mReSchedulePostAnimationCallback) {                postOnAnimation();            }        }        voID postOnAnimation() {            if (meatRunOnAnimationRequest) {                mReSchedulePostAnimationCallback = true;            } else {                removeCallbacks(this);                VIEwCompat.postOnAnimation(CustomScrollVIEw.this, this);            }        }    }    private voID constrainScrollBy(int dx, int dy) {        Rect vIEwport = new Rect();        getGlobalVisibleRect(vIEwport);        int height = vIEwport.height();        int wIDth = vIEwport.wIDth();        int scrollX = getScrollX();        int scrollY = getScrollY();        //右边界        if (mWIDth - scrollX - dx < wIDth) {            dx = mWIDth - scrollX - wIDth;        }        //左边界        if (-scrollX - dx > 0) {            dx = -scrollX;        }        //下边界        if (mHeight - scrollY - dy < height) {            dy = mHeight - scrollY - height;        }        //上边界        if (scrollY + dy < 0) {            dy = -scrollY;        }        scrollBy(dx, dy);    }}

 

 

 

 

 

 

总结

以上是内存溢出为你收集整理的android自定义控件的惯性滑动全部内容,希望文章能够帮你解决android自定义控件的惯性滑动所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1105040.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-28
下一篇 2022-05-28

发表评论

登录后才能评论

评论列表(0条)

保存