美文网首页
View的滑动

View的滑动

作者: blueizz | 来源:发表于2018-10-11 17:38 被阅读0次

一、实现View滑动的方式

  • offsetLeftAndRight() 和 offsetTopAndBottom()
    View的位置主要是由它的四个顶点来决定,分别对应于View的四个属性:left、right、top、bottom。Android提供了offsetLeftAndRight()来改变left和right的值,用 offsetTopAndBottom()来改变top和bottom的值。
offsetLeftAndRight(offsetX)
offsetTopAndBottom(offsetY)
  • LayoutParams
    LayoutParams保存了一个View的布局参数,可以通过动态改变LayoutParams中的布局参数来达到改变View的位置效果。
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) mView.getLayoutParams();
params.leftMargin = mView.getLeft() + offsetX;
params.topMargin = mView.getTop() + offsetY;
mView.setLayoutParams(params);
  • 属性动画
    使用动画来移动View,主要是操作View的translationX和translationY属性
float x = mView.getX();
float y = mView.getY();
ObjectAnimator.ofFloat(mView, "translationX", x , x + offsetX).start();
ObjectAnimator.ofFloat(mView, "translationY", y , y + offsetY).start();
  • scrollTo与scrollBy
    使用scrollTo和scrollBy来实现View的滑动,实际上是让View的内容移动。如果在ViewGroup中使用scrollTo()和scrollBy()方法,那么移动的将是所有的子View,如果在View中使用,那么移动的将是View的内容。当传入的参数是正数时,View的内容向左移;当传入的参数是负数时,View的内容向右移。

  • Scroller
    Scroller本身无法让View弹性滑动,它需要和View的computeScroll方法配合使用才能实现View的滑动。使用Scroller的基本流程:
    1、生成Scroller对象
    2、调用startScroll设置滑动的起点和行程距离开始滚动
    startScroll(int startX, int startY, int dx, int dy)
    startScroll(int startX, int startY, int dx, int dy, int duration)
    参数含义:
    startX:滑动的起始点x坐标
    startY:滑动的起始点y坐标
    dx:x轴偏移量向左为负,向右为正(即负值向右移,正值向左移)
    dy:y轴偏移量向左为负,向右为正(即负值向右移,正值向左移)
    duration:完成滑动所需的时间,默认为250ms
    3、在View的computeScroll中使用computeScrollOffset判断滑动完成,调用scrollTo方法,实现真正的滑动

    Scroller mScroller = new Scroller(context);

    /**
     * 滑动到指定位置
     *
     * @param destX 目标x坐标
     * @param destY 目标y坐标
     */
    public void smoothScrollTo(int destX, int destY) {
        int scrollX = getScrollX();
        int scrollY = getScrollY();
        int offsetX = destX - scrollX;
        int offsetY = destY - scrollY;
        mScroller.startScroll(scrollX, scrollY, offsetX, offsetY);
        invalidate();
    }

    @Override
    public void computeScroll() {
        if (mScroller.computeScrollOffset()) {
            scrollTo(mScroller.getCurrX(), mScroller.getCurrY());
            postInvalidate();
        }
    }

二、各种滑动方式的对比

  • offsetLeftAndRight / offsetTopAndBottom:操作简单
  • LayoutParams:操作稍微复杂,适用于有交互的View
  • 属性动画:操作简单,主要适用于没有交互的View和实现复杂的动画效果
  • scrollTo / scrollBy:操作简单,适合对View内容的滑动
  • Scroller:弹性滑动

相关文章

网友评论

      本文标题:View的滑动

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