ViewDragHelper拖拽帮助类-1
1、ViewDragHelper说明
Google2003年IO大会提出,解决控件拖拽移动问题
2、ViewDragHelper拖拽的使用
2.1创建拖拽对象
三个参数的方法多了拖拽敏感度,值越大敏感度越小,这里使用默认值两个参数的
// 两个参数的意思 // 拖拽View的父ViewGroup // 拖拽回调 ViewDragHelper mDragHelper = ViewDragHelper.create(this, mCallBack);
2.2是否拦截事件
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
// 决定是否拦截事件
return mDragHelper.shouldInterceptTouchEvent(ev);
}
2.3事件处理
@Override
public boolean onTouchEvent(MotionEvent event) {
// 处理事件
try {
mDragHelper.processTouchEvent(event);
} catch (Exception e) {
// 多点触摸可能会有异常
e.printStackTrace();
}
return true;
}
2.4在回调方法中处理拖拽
这里先介绍两个方法:
1、ViewGroup中哪个控件可以拖拽
2、拖拽的该控件移动的位置
ViewDragHelper.Callback mCallBack = new Callback() {
// 决定是否拖拽
// child 当前拖拽的View
// pointerId 区分多点触摸的Id
@Override
public boolean tryCaptureView(View child, int pointerId) {
// 只允许主面板拖拽
return child == mMainContent;
}
// 根据建议值返回移动的位置
// 不重写默认为0,则不能移动
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
return left;
}
};
3、补充
ViewGroup的一个方法
// XML填充结束,所有子View添加进来时调用
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if(getChildCount() < 2){
throw new IllegalStateException("至少两个View");
}
if(!(getChildAt(0) instanceof ViewGroup && getChildAt(0) instanceof ViewGroup)){
throw new IllegalStateException("View必须是ViewGroup的子类");
}
mLeftContent = (ViewGroup) getChildAt(0);
mMainContent = (ViewGroup) getChildAt(0);
}
浙公网安备 33010602011771号