Android自定义View实现自动吸附功能
程序员文章站
2022-06-24 16:10:29
本文实例为大家分享了android实现自动吸附功能的具体代码,供大家参考,具体内容如下
1.简述
最近开发app过程中要实现拖动view后要可以自动吸附功能,所以需要自定义view...
本文实例为大家分享了android实现自动吸附功能的具体代码,供大家参考,具体内容如下
1.简述
最近开发app过程中要实现拖动view后要可以自动吸附功能,所以需要自定义view来在ontouchevent中来利用动画来实现此功能
2.功能代码部分
import android.content.context; import android.graphics.canvas; import android.util.attributeset; import android.util.log; import android.view.motionevent; import android.view.animation.decelerateinterpolator; import android.widget.imageview; public class adsorbentviews extends imageview { private int maxwidth; private int maxheight; private int viewwidth; private int viewheight; private float downx; private float downy; private context mcontext; public customviews(context context) { this(context, null); } public customviews(context context, attributeset attrs) { this(context, attrs, 0); } public customviews(context context, attributeset attrs, int defstyleattr) { super(context, attrs, defstyleattr); mcontext = context; } @override protected void ondraw(canvas canvas) { super.ondraw(canvas); displaymetrics outmetrics = new displaymetrics(); windowmanager windowmanager = (windowmanager) mcontext.getsystemservice(context.window_service); windowmanager.getdefaultdisplay().getrealmetrics(outmetrics); //屏幕的宽度 maxwidth = outmetrics.widthpixels; //屏幕的高度 maxheight = outmetrics.heightpixels; /** * 控件的宽高 */ viewwidth = canvas.getwidth(); viewheight = canvas.getheight(); } @override public boolean ontouchevent(motionevent event) { switch (event.getaction()) { case motionevent.action_down: clearanimation(); downx = event.getx(); downy = event.gety(); return true; case motionevent.action_move: float movex = event.getrawx() - downx; float movey = 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); return true; case motionevent.action_up: //做吸附效果 float centerx = getx() + viewwidth / 2; if (centerx > maxwidth/2){ //靠右吸附 animate().setinterpolator(new decelerateinterpolator()) .setduration(500) .x(maxwidth-viewwidth) .y(maxheight-viewheight) .start(); }else { animate().setinterpolator(new decelerateinterpolator()) .setduration(500) .x(0) .y(maxheight-viewheight) .start(); } return true; default: return super.ontouchevent(event); } } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。