美文网首页
ViewDragHelper

ViewDragHelper

作者: 卖梦想的男孩 | 来源:发表于2016-11-17 17:03 被阅读23次

ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number* of useful operations and state tracking for allowing a user to drag and reposition* views within their parent ViewGroup.

ViewDragHelper在support v4中,目的很明确,就是方便ViewGroup管理子View的拖拽和摆放。

1. 创建

Helper提供了两个静态方法

 - forParent 监控的父类
 - sensitivity  灵敏度,越大越灵敏,默认1
 - cb 各种回调事件
public static ViewDragHelper create(ViewGroup forParent, Callback cb);
public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb);

2. 事件拦截

@Overridepublic boolean onInterceptTouchEvent(MotionEvent ev) {
  return mDragHelper.shouldInterceptTouchEvent(ev)
}

@Overridepublic boolean onTouchEvent(MotionEvent ev) {  
  mDragHelper.processTouchEvent(ev);   
  return super.onTouchEvent(ev);
}

3. 回调管理

  • 控制触摸的View是否支持拖拽
public boolean tryCaptureView(final View child, final int pointerId)
  • 找到支持拖拽的View
public void onViewCaptured(final View capturedChild, final int activePointerId)
  • 拖拽的View位置发生改变
public void onViewPositionChanged(final View changedView, final int left, final int top, final int dx, final int dy)
  • 拖拽的View被松开
public void onViewReleased(final View releasedChild, final float xvel, final float yvel)
  • 父View边缘被触摸
public void onEdgeTouched(final int edgeFlags, final int pointerId)
  • 检查某个边缘是否锁住(即不支持拖拽)
public boolean onEdgeLock(final int edgeFlags)
  • 从某个边缘开始拖拽
public void onEdgeDragStarted(final int edgeFlags, final int pointerId)
  • 获取某个位置的View层级
public int getOrderedChildIndex(final int index)
  • 获取在View某方向上可拖拽的范围 0为该方向不可拖拽(实际为该范围内不强制获取事件,如果有点击之类的事件,则不可拖拽。当范围为整个View的时候,优先处理拖拽)
public int getViewHorizontalDragRange(final View child)
public int getViewVerticalDragRange(final View child) 
  • 获取View在某方向上可移动的位置,left | top
public int clampViewPositionHorizontal(final View child, final int left, final int dx)
public int clampViewPositionVertical(final View child, final int top, final int dy)

Helper 常用方法

  • 基本使用时回调中捕获View,针对的是拖拽View
  • 释放后可以友好的设置View位置
public boolean settleCapturedViewAt(int finalLeft, int finalTop)

需要配合computeScroll完成动画,实质是调用Scroller的startScroll

@Overridepublic void computeScroll() {   
 if(mDragHelper.continueSettling(true)) {
        postInvalidate();  
}
}
  • 边缘检测灵活设置被或拽的对象
public void setEdgeTrackingEnabled(int edgeFlags)

一般配合回调中的边缘事件,手动设置捕获的View,然后做移动

public void captureChildView(View childView, int activePointerId)

相关文章

网友评论

      本文标题:ViewDragHelper

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