ViewDragHelper几个方法的理解

转载标明出处:http://blog.csdn.net/coder_nice

smoothSlideViewTo()

通过此方法可以把父布局中某一个子View移动到指定的左边,移动过程会调用ViewDragHelper.Callback中的onViewPositionChanged()、onViewReleased()、clampViewPositionVertical等方法。
换句话说该方法就相当于模仿了人为的拖拽子View到特点坐标的过程。
可以通过此方法实现手势惯性的效果(只要手指轻轻滑动一段距离,判断用户确实想把子View滑动到目标坐标,即使用户中途松手或者未能滑动到目标坐标,也会自动把子View滑动到目标位置)
代码通常这样写:

if (mDragHelper.smoothSlideViewTo(mHeaderView, x, y)) {
            ViewCompat.postInvalidateOnAnimation(this);
            postInvalidate();
            return true;
        }

settleCapturedViewAt()

该方法与smoothSlideViewTo所实现的效果是一样的,区别在于smoothSlideViewTo()是指定一个子View,而settleCapturedViewAt()是在ViewDragHelper.Callback的onViewReleased()方法中获取当前释放的子View,然后实现手势惯性的效果。
代码如下:


    @Override
        public void onViewReleased(View releasedChild, float xvel, float yvel) {
            int top = getPaddingTop();
            if (yvel > 0 || (yvel == 0 && mDragOffset > 0.5f)) {
                top += mDragRange;
            }
        mDragHelper.settleCapturedViewAt(releasedChild.getLeft(), top);
            invalidate();
        }

先写到这里,另外的方法后续补上来。。。。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
ViewDragHelper是一个帮助我们实现View拖拽和滑动效果的工具类,使用它可以简单地实现一些常见的交互效果,例如拖拽、滑动、边缘拖拽等。以下是使用ViewDragHelper的一般步骤: 1. 创建ViewDragHelper对象 ``` ViewDragHelper mDragHelper = ViewDragHelper.create(parentView, 1.0f, new DragHelperCallback()); ``` 2. 编写DragHelperCallback类 ``` private class DragHelperCallback extends ViewDragHelper.Callback { // 重写tryCaptureView方法,判断是否捕获当前View @Override public boolean tryCaptureView(View child, int pointerId) { return true; } // 重写clampViewPositionHorizontal和clampViewPositionVertical方法,返回拖拽后View的位置 @Override public int clampViewPositionHorizontal(View child, int left, int dx) { final int leftBound = getPaddingLeft(); final int rightBound = getWidth() - child.getWidth() - leftBound; final int newLeft = Math.min(Math.max(left, leftBound), rightBound); return newLeft; } @Override public int clampViewPositionVertical(View child, int top, int dy) { final int topBound = getPaddingTop(); final int bottomBound = getHeight() - child.getHeight() - topBound; final int newTop = Math.min(Math.max(top, topBound), bottomBound); return newTop; } } ``` 3. 在View的onTouchEvent中处理事件 ``` @Override public boolean onTouchEvent(MotionEvent event) { mDragHelper.processTouchEvent(event); return true; } ``` 4. 在View的onDraw方法中绘制View ``` @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 绘制View } ``` 以上是使用ViewDragHelper的一般步骤,具体使用还需要根据实际需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值