Android中View的滑动

作者: cooperise | 来源:发表于2016-08-18 23:31 被阅读74次

    使用scrollTo/scrollBy (View中提供的方法)

    scrollBy实际上也是调用了scrollTo的方法,它是实现了基于当前位置的相对滑动,而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;  
            onScrollChanged(mScrollX, mScrollY, oldX, oldY);  
            if (!awakenScrollBars()) {  
                invalidate();  
            }  
        }  
    }  
      
    /** 
     * 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);  
    }  
    

    scrollTo和scrollBy只能改变View内容的位置而不能改变View在布局中的位置。scrollTo用mScrollX和mScrollY记录了滚动的偏移量,滑动过程中,如果从左向右滑动,那么mScrollX为负值,反之为正值;如果从上向下滑动,那么mScrollY为负值,反之为正值;

    使用动画

    使用动画来移动View,主要是操作View的translationX和translationY属性

    • 传统View动画,100ms内将View从原始位置向右下角移动100个像素
    <set xmlns:android="http://schemas.android.com/apk/res/android"
      android:fillAfter="true"
      android:zAdjustment="normal">
    
        <translate
           android:duration="100"
           android:fromXDelta="0"
           android:fromYDelta="0"
           android:interpolator="@android:anim/linear_interpolator"
           android:toXDelta="100"
           android:toYDelta="100"/>
    </set>
    

    如果fillAfter为false,那么在动画消失的一刹那,瞬间恢复到动画开始前的位置,为true则会保留动画更改后的位置

    • 属性动画,100ms内将View从原始位置向右移动100个像素
    ObjectAnimator.ofFloat(targetView,"translationX",0,100).setDuration(100).start();
    

    上面提到的View动画并不能真正改变View的位置,如果View上有点击事件,那么该事件的触发依旧在View开始动画前的位置上

    改变布局参数

    改变布局参数,即改变LayoutParams

    MarginLayoutParams params = (MarginLayoutParams)mButton.getLayoutParams();
    params.width += 100;
    params.leftMargin += 100;
    mButton.requestLayout();
    // 或者mButton.setLayoutParams(params);
    
    scrollTo/scrollBy 操作简单,适合对View内容的移动
    动画 操作简单,主要适用于没有交互的View和实现复杂的动画效果
    改变布局参数 操作稍微复杂,适用于有交互的View

    相关文章

      网友评论

        本文标题:Android中View的滑动

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