Android自定义View实现自动吸附功能
本文实例为大家分享了Android实现自动吸附功能的具体代码,供大家参考,具体内容如下
1.简述
最近开发app过程中要实现拖动view后要可以自动吸附功能,所以需要自定义view来在onTouchEvent中来利用动画来实现此功能
2.功能代码部分
importandroid.content.Context; importandroid.graphics.Canvas; importandroid.util.AttributeSet; importandroid.util.Log; importandroid.view.MotionEvent; importandroid.view.animation.DecelerateInterpolator; importandroid.widget.ImageView; publicclassAdsorbentViewsextendsImageView{ privateintmaxWidth; privateintmaxHeight; privateintviewWidth; privateintviewHeight; privatefloatdownx; privatefloatdowny; privateContextmContext; publicCustomViews(Contextcontext){ this(context,null); } publicCustomViews(Contextcontext,AttributeSetattrs){ this(context,attrs,0); } publicCustomViews(Contextcontext,AttributeSetattrs,intdefStyleAttr){ super(context,attrs,defStyleAttr); mContext=context; } @Override protectedvoidonDraw(Canvascanvas){ super.onDraw(canvas); DisplayMetricsoutMetrics=newDisplayMetrics(); WindowManagerwindowManager=(WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE); windowManager.getDefaultDisplay().getRealMetrics(outMetrics); //屏幕的宽度 maxWidth=outMetrics.widthPixels; //屏幕的高度 maxHeight=outMetrics.heightPixels; /** *控件的宽高 */ viewWidth=canvas.getWidth(); viewHeight=canvas.getHeight(); } @Override publicbooleanonTouchEvent(MotionEventevent){ switch(event.getAction()){ caseMotionEvent.ACTION_DOWN: clearAnimation(); downx=event.getX(); downy=event.getY(); returntrue; caseMotionEvent.ACTION_MOVE: floatmoveX=event.getRawX()-downx; floatmoveY=event.getRawY()-downy; moveX=moveX<0?0:(moveX+viewWidth>maxWidth)?(maxWidth-viewWidth):moveX; moveY=moveY<0?0:(moveY+viewHeight)>maxHeight?(maxHeight-viewHeight):moveY; this.setY(moveY); this.setX(moveX); returntrue; caseMotionEvent.ACTION_UP: //做吸附效果 floatcenterX=getX()+viewWidth/2; if(centerX>maxWidth/2){ //靠右吸附 animate().setInterpolator(newDecelerateInterpolator()) .setDuration(500) .x(maxWidth-viewWidth) .y(maxHeight-viewHeight) .start(); }else{ animate().setInterpolator(newDecelerateInterpolator()) .setDuration(500) .x(0) .y(maxHeight-viewHeight) .start(); } returntrue; default: returnsuper.onTouchEvent(event); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。