您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關怎么在Android中通過自定義View實現一個自動吸附功能,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
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); } } }
看完上述內容,你們對怎么在Android中通過自定義View實現一個自動吸附功能有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。