转自:可以拖拽的ViewGroup,仿微信拖拽缩放关闭_buyaoshitududongwo的博客-CSDN博客
此处利用了ViewDragHelper类
内部设置了一个监听,松手进行关闭即可
importandroid.content.Context;
importandroid.support.annotation.NonNull;
importandroid.support.annotation.Nullable;
importandroid.support.v4.view.ViewCompat;
importandroid.support.v4.widget.ViewDragHelper;
importandroid.util.AttributeSet;
importandroid.view.MotionEvent;
importandroid.view.View;
importandroid.widget.FrameLayout;
publicclassDragViewGrouopextendsFrameLayout{
privateViewDragHelper dragHelper;
privateintmOldLeft;
privateintmOldTop;
privateintmHeight;
privatefloatmScaleValue;
privatefloatmMinRate =0.4f;
publicDragViewGrouop(@NonNullContext context){
this(context,null);
}
publicDragViewGrouop(@NonNullContext context,@NullableAttributeSet attrs){
this(context, attrs,0);
}
publicDragViewGrouop(@NonNullContext context,@NullableAttributeSet attrs,intdefStyleAttr){
super(context, attrs, defStyleAttr,0);
init();
}
privatevoidinit(){
dragHelper = ViewDragHelper.create(this,newViewDragHelper.Callback() {
@Override
publicbooleantryCaptureView(View child,intpointerId){
returntrue;
}
@Override
publicvoidonViewReleased(View releasedChild,floatxvel,floatyvel){
if(dragListener !=null&& mScaleValue < mMinRate) {
dragListener.onViewReleased();
}else{
dragHelper.settleCapturedViewAt(mOldLeft, mOldTop);
invalidate();
ViewCompat.animate(releasedChild).scaleX(1).setDuration(0);
}
}
@Override
publicvoidonViewCaptured(View capturedChild,intactivePointerId){
mOldLeft = capturedChild.getLeft();
mOldTop = capturedChild.getTop();
}
@Override
publicintclampViewPositionVertical(View child,inttop,intdy){
mScaleValue =1.00f- Math.abs((top - mOldTop) *1.0f/ (mHeight - mOldTop));
ViewCompat.animate(child).scaleX(mScaleValue).setDuration(0);
returntop;
}
@Override
publicintclampViewPositionHorizontal(View child,intleft,intdx){
returnleft;
}
});
}
@Override
publicvoidcomputeScroll(){
super.computeScroll();
if(dragHelper !=null&& dragHelper.continueSettling(true)) {
invalidate();
}
}
@Override
protectedvoidonSizeChanged(intw,inth,intoldw,intoldh){
super.onSizeChanged(w, h, oldw, oldh);
mHeight = h;
}
@Override
publicbooleanonInterceptTouchEvent(MotionEvent ev){
if(dragHelper !=null) {
returndragHelper.shouldInterceptTouchEvent(ev);
}
returnsuper.onInterceptTouchEvent(ev);
}
@Override
publicbooleanonTouchEvent(MotionEvent event){
if(dragHelper !=null) {
dragHelper.processTouchEvent(event);
}
returntrue;
}
privateDragListener dragListener;
publicvoidsetOnDragListener(DragListener dragListener){
this.dragListener = dragListener;
}
publicinterfaceDragListener{
voidonViewReleased();
}
网友评论