本文实现:将图片任意拖动,如果拖动到正确位置则成功,若抬起手时时错误位置则自动回到原位。 定义 private ImageView img; private ImageView
本文实现:将图片任意拖动,如果拖动到正确位置则成功,若抬起手时时错误位置则自动回到原位。
定义
private ImageView img;
private ImageView imageView;
//容器的宽高,需要在屏幕绘制好之后才能获取
private int containerWidth;
private int containerHeight;
private float lastX, lastY;
//获取需要拖动到的正确位置
private int[] imgPosition = new int[2];
private int height;
private int width;
在屏幕绘制好之后获取宽高和位置
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
// 这里来获取容器的宽和高
if (hasFocus) {
containerHeight = sunPage.getHeight();
containerWidth = sunPage.getWidth();
}
//获取需要拖动到的正确位置,img处
img.getLocationInWindow(imgPosition);
height = img.getMeasuredHeight();
width = img.getMeasuredWidth();
}
手势事件
imageView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
//手指在屏幕位置getRawX() getRawY()
lastX = event.getRawX();
lastY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
// 不要直接用getX和getY,这两个获取的数据已经是经过处理的,容易出现图片抖动的情况
float distanceX = xx - event.getRawX();
float distanceY = yy - event.getRawY();
float nextY = imageView.getY() - distanceY;
float nextX = imageView.getX() - distanceX;
// 不能移出屏幕
if (nextY < 0) {
nextY = 0;
} else if (nextY > containerHeight - imageView.getHeight()) {
nextY = containerHeight - imageView.getHeight();
}
if (nextX < 0)
nextX = 0;
else if (nextX > containerWidth - imageView.getWidth())
nextX = containerWidth - imageView.getWidth();
// 属性动画移动
ObjectAnimator y = ObjectAnimator.ofFloat(imageView, "y", imageView.getY(), nextY);
ObjectAnimator x = ObjectAnimator.ofFloat(imageView, "x", imageView.getX(), nextX);
animatorSet.playTogether(x, y);
animatorSet.setDuration(0);
animatorSet.start();
lastX = event.getRawX();
lastY = event.getRawY();
if (correct(lastX, lastY, imgPosition, m)) {
//正确后的事情
}
break;
case MotionEvent.ACTION_UP:
//抬起手后自动弹回原处,监听animatorSet
animatorSet.cancel();
break;
}
return true;
}
});
判断拖动是否正确,m是img的半径,拖动结合的难易可以自己调剂算法
//判断拖动是否正确,m是img的半径,拖动结合的难易可以自己调剂算法
private boolean correct(float x, float y, int[] a, int m) {
float s = (float) Math.sqrt((x - a[0]) * (x - a[0]) + (y - a[1]) * (y - a[1]) - (x - a[0]) * (y - a[1]));
if (s <= ActivityUtils.dip2px(HomeGameActivity.this, m)) {
return true;
}
return false;
}
监听animatorSet,cancle时imageview返回原处
animatorSet.addListener(new Animator.AnimatorListener() {
@Override
public void onAnimationStart(Animator animation) {
}
@Override
public void onAnimationEnd(Animator animation) {
}
@Override
public void onAnimationCancel(Animator animation) {
imageView.setTranslationY(0);
imageView.setTranslationX(0);
}
@Override
public void onAnimationRepeat(Animator animation) {
}
});
--结束END--
本文标题: Android实现view拖动到任意位置
本文链接: https://lsjlt.com/news/123566.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-21
2023-10-28
2023-10-28
2023-10-27
2023-10-27
2023-10-27
2023-10-27
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0