public DragViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragCallback());
}
…
}
其中ViewDragCallback是我自己创建的内部类,继承自ViewDragHelper.Callback实现类。
private static class ViewDragCallback extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(@NonNull View child, int pointerId) {
// 决定child是否可以被拖拽,具体见下文源码分析
return true;
}
@Override
public int clampViewPositionHorizontal(@NonNull View child, int left, int dx) {
// 可决定child横向的偏移计算,见下文
return left;
}
@Override
public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
// 可决定child竖向的偏移计算,见下文
return top;
}
}
重写DragViewGroup的方法onInterceptHoverEvent和onTouchEvent方法:
public class DragViewGroup extends RelativeLayout {
…
@Override
public boolean onInterceptHoverEvent(MotionEvent event) {
return mDragHelper.shouldInterceptTouchEvent(event);
}
@SuppressLint(“ClickableViewAccessibility”)
@Override
public boolean onTouchEvent(MotionEvent event) {
mDragHelper.processTouchEvent(event);
return true;
}
…
}
这是我们的layout文件,其中DragViewGroup是我们上面定义的ViewGroup,TextView就是待拖拽的child view。
<com.blog.a.drag.DragViewGroup
android:layout_width=“match_parent”
android:layout_height=“match_parent”
</com.blog.a.drag.DragViewGroup>
是不是非常省事,博客的栗子我都上传到了gitHub上,感兴趣的可以下载看下。
源码
本篇文章主要分析下,当触摸事件开始到结束,processTouchEvent的处理过程:
public boolean onTouchEvent(MotionEvent event) {
mDragHelper.processTouchEvent(event);
return true;
}
MotionEvent.ACTION_DOWN
当手指刚接触屏幕时,会触发ACTION_DOWN 事件,通过MotionEvent我们能获取到点击事件发生的 x, y 坐标,注意这里的get