用户体验(1)-交互实现

1,要在交互的时候实现比较好的效果,手势和滑动是最基础的交互方式,所以必不可少的要用Scroller和GestureDetector这两个类。

2,手势滑动一般与抛掷fling又关联起来,实现比较平缓的过渡效果。

3,实现这样的效果,需要以下基础知识

(1)认识Scroller类的fling函数

    /**
     * Start scrolling based on a fling gesture. The distance travelled will
     * depend on the initial velocity of the fling.
     * 
     * @param startX Starting point of the scroll (X)
     * @param startY Starting point of the scroll (Y)
     * @param velocityX Initial velocity of the fling (X) measured in pixels per
     *        second.
     * @param velocityY Initial velocity of the fling (Y) measured in pixels per
     *        second
     * @param minX Minimum X value. The scroller will not scroll past this
     *        point.
     * @param maxX Maximum X value. The scroller will not scroll past this
     *        point.
     * @param minY Minimum Y value. The scroller will not scroll past this
     *        point.
     * @param maxY Maximum Y value. The scroller will not scroll past this
     *        point.
     */
    public void fling(int startX, int startY, int velocityX, int velocityY,
            int minX, int maxX, int minY, int maxY) 

源码是上边的代码,startX:起始X位置,startY:起始Y,velocityX:X方向滑动速度,velocityY:Y方向滑动速度,minX:水平滑动最小值,maxX:水平滑动最大值,minY:垂直滑动最小值,maxY:垂直滑动最大值。

(2)滑动过程:调用fling或者调用startScroll都是对Scroller类中的起始位置和终止位置进行设置,要实现真正的滑动,必须重写View类的computeScroll在里边改变参数,并主动调用invalidate刷新当前view,就可以看到效果,注意:这里computeScroll和draw实际上是相互调用的关系,计算滚动距离-》刷新-》在计算距离-》刷新,所以,需要在computeScroll中指定什么时候不需要刷新了,也就是跳出条件,用computeScrollOffset去判断跳出条件。

(3)android坐标系认识:

在onscroll滑动时,我们看下具体怎么对应各个参数值,

 /**
         * Notified when a scroll occurs with the initial on down {@link MotionEvent} and the
         * current move {@link MotionEvent}. The distance in x and y is also supplied for
         * convenience.
         *
         * @param e1 The first down motion event that started the scrolling.
         * @param e2 The move motion event that triggered the current onScroll.
         * @param distanceX The distance along the X axis that has been scrolled since the last
         *              call to onScroll. This is NOT the distance between {@code e1}
         *              and {@code e2}.
         * @param distanceY The distance along the Y axis that has been scrolled since the last
         *              call to onScroll. This is NOT the distance between {@code e1}
         *              and {@code e2}.
         * @return true if the event is consumed, else false
         */
        boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY);

第三个参数:distanceX,这个距离不是e1起始到e2的距离,而是上次调用onscroll到这次调用scroll滑动的距离,也就是用上次调用onscroll时的x值-本次调用onscroll时的x值所得的值,那么很明显,如果往左滑动这个值为正,往右滑动这个值为负值。

具体如何理解,上图:

假设有这个图片,现在数字1、2显示在如图的位置,如果想要做向左滚动的效果,假设第一次向左滚动单位为5,那么根据onscroll函数参数的定义,这个distanceX=0-(-5)=5,在ondraw中,只需要将起始绘制的点调整为0-distanceX=-5就可以了,也就是说,原先在原点显示的内容现在你去x=-5的地方显示吧,这样就完成了滚动。

原文地址:https://www.cnblogs.com/hpustudent/p/4557376.html