12.View的滑动

1.scrollTo和ScrollBy
    为了实现滑动,View提供了两个方法来让我们实现这个功能,那就是scrollTo和scrollBy方法,
    scrollTo的方法如下:
     
/**
     * Set the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the x position to scroll to
     * @param y the y position to scroll to
     */
    public void scrollTo(int x, int y) {
        if (mScrollX != x || mScrollY != y) {
            int oldX = mScrollX;
            int oldY = mScrollY;
            mScrollX = x;
            mScrollY = y;
            //用于通知父控件需要清空这个View的缓存
            invalidateParentCaches();
            onScrollChanged(mScrollX, mScrollY, oldX, oldY);
            
            if (!awakenScrollBars()) {
                postInvalidateOnAnimation();
            }
        }
    }


    接下来我们来看这个方法,这个方法的参数x,y分别代表,我们想要让这个View偏离最初位置的大小,比如x为100,那么就偏离最初100个像素点,其中,从左向右滑动是负的,从右向左是正的,View从上向下是负的,从下往上滑动是负的,
   这个方法是绝对滑动,比如当前横纵偏离都是90,这时候参数为scroll( 100 , 100 ) 那么做的操作就是向上滑动10,向左滑动10,。
    接下来我们看到invalidateParentCaches 这个方法,这个方法是用于通知父控件,当前的控件已经失效了,要让父控件清空当前这个View的缓存,并且重新创建这个View。
    awakeScrollBars 返回为true代表着有动画正在进行,为false就是其他情况。当有动画在进行的时候,我们就不应该继续执行滚动动画,而当前没有动画在进行,我们就调用postInvalidateOnAnimation 这个,这个方法支持在异步线程刷新UI,并且带有动画效果。
    
    接下来介绍scrollBy方法:
   
    /**
     * Move the scrolled position of your view. This will cause a call to
     * {@link #onScrollChanged(int, int, int, int)} and the view will be
     * invalidated.
     * @param x the amount of pixels to scroll by horizontally
     * @param y the amount of pixels to scroll by vertically
     */
    public void scrollBy(int x, int y) {
        scrollTo(mScrollX + x, mScrollY + y);
    }



   可以看到,scrollBy方法就是基于scrollTo方法,scrollBy方法是相对偏移,比如当前滚动为90 90 ,我们需要调用scrollByt(10, 10 ) 结果,滚动偏移就成了100 , 100 。

2. 使用动画
    使用动画也可以完成滑动效果,不过,动画的交互感会比较弱,因为上面的第一种方法的滚动偏移量,是可以动态改变的,这意味着什么?这意味着,我们可以在onTouchEvent去控制,可以结合用户的手势来完成各种滚动效果,在这边,我们就暂时不详细谈了。接下来我们来复习下动画的使用。
    第一种方法是使用XML
   
 <?xml version="1.0" encoding="utf-8"?>
     <set xmlns:android="http://schemas.android.com/apk/res/android"
            android:fillAfter="true"
            android:zAdjustment="normal">
            <translate
                android:duration="100"
                android:fromXDelta="0"
                android:formXDelta="0"
                android:interpolator="@android:anim/linear_interpolator"
                android:toXDelta="100"
                android:toYDelta="100"   />    
    </set>

        这个方法会让我们把View从原始位置往下移动100个像素
另外一种是使用属性动画
        ObjectAnimator.ofFloat( tragetView,"translationX",0,100).setDuraltion( 100 ).start();
    动画的缺点主要是,执行动画过程中,是不可逆的。
 3.改变布局参数
 尽管这里我不太愿意介绍,但是,其实setLayoutParams也可以用于做动画效果,但是,这边不推荐使用,因为当你使用的是比较复杂的控件的时候,尤其是带图片资源,setLayoutParams带来的开销是很大的,耗费CPU资源较多,在一些低配置的机器上,运行的效果不理想。
但是,在使用拖拽效果的时候,一些小元素还是很适合用setLayoutParams的。                                    0.
  
    

猜你喜欢

转载自blog.csdn.net/savelove911/article/details/51352612
今日推荐