Android中怎么通过自定义View实现自动吸附功能,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。
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); } }}
看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。