ViewDragHelper空指针异常笔记

ViewDrapHelper简介

在实际项目中,有时会需求一个ViewGroup中的子view能够随着用户手指的拖动而发生相应的变化,如随着手指的拖动而运动等,但处理onTouchEvent和onInterceptTouchEvent事件比较麻烦且易出错,因此google提供了一个类:ViewDrapHelper类,位于support-v4包中。该类对用户拖动view动作进行一些列封装,方便开发者使用。

ViewDrapHelper的创建和使用

创建一个ViewDrapHelper事例代码:
ViewDragHelper dragHelper = ViewDragHelper.create(ViewGroup forParent, Callback cb)

当创建一个ViewDrapHelper时,需要传递一个ViewGroup对象和一个用于处理子view对用户手指拖动如何反应的callback对象。

Callback类常用方法

//用于判断child是否可以被捕获(简单理解就是可以随手指移动)
public boolean tryCaptureView(View child, int pointerId)

//用于限制child水平或垂直方向的边界限制,但该限制只对child离开用户手指后缓慢移动(复位或其他)起作用,而对手指拖动无效
public int getViewHorizontalDragRange(View child)
public int getViewVerticalDragRange(View child)

//真正用于限制child的边界范围,其中left=child.getLeft()+dx
public int clampViewPositionHorizontal(View child, int left, int dx)
public int clampViewPositionVertical(View child, int top, int dy)

//当子view的位置发生变化是调用,dx和dy为实际水平和垂直方向移动的距离 应用场景:多个view随手指拖动的changedView做伴随移动等
public void onViewPositionChanged(View changedView, int left, int top,int dx, int dy)

//当手指离开子view是调用
应用场景:releasedChild缓慢归位等
public void onViewReleased(View releasedChild, float xvel, float yvel)

另外,ViewDrapHelper还对Scroller进行了封装
使用案例代码:

viewDrapHelper.smoothSlideViewTo(View child, int finalLeft, int finalTop)

@Override
    public void computeScroll() {
        super.computeScroll();
        if (dragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(SwipLayout.this);
        }
    }

空指针异常

在使用ViewDrapHelper时,必须要重写ViewGroup的onTouchEvent和onInterceptTouchEvent两个方法,并且在这两个方法中调用viewDrapHelper.processTouchEvent(event)和viewDrapHelper.shouldInterceptTouchEvent(ev),出现空指针异常就是在这两个方法中摸个方法没有将MotionEvent事件传递给viewDrapHelper;
错误代码:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {

    if (XXXXX) {
        return true;
        }
    return viewDrapHelper.shouldInterceptTouchEvent(ev);
    }

错误分析,在onInterceptTouchEvent方法中,当我们处理拦截事件时,对与只有条件XXXXX不成立时才传递给viewDrapHelper MotionEvent 事件,否则viewDrapHelper 拿不到处理事件,当在ontouchevent方法中调用viewDrapHelper.processTouchEvent(event)方法,会报空指针异常。

正确代码:

@Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean res = dragHelper.shouldInterceptTouchEvent(ev);
        if (XXXXX) {
            res = true;
        }
        return res;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值