如何确定ImageView从其原始位置移动一定距离的时刻?



这是我的第一个问题,很抱歉。

在我的应用中,我有一个动画的ImageView。如果有人点击它,它会移动到随机坐标。这是必要的,在瞬间,当ImageView克服了一定的距离(初始设置)吐司出现。我的问题是,无论ImageView是否覆盖了给定的距离,Toast都会出现很多次。需要你的建议,我该如何解决它。提前感谢!

private final int MAX_LENGTH = 420;
private int xRand, yRand;
private int xStart, yStart;
private View unlimitePlayView;
private ImageView circle;
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
unlimitePlayView = inflater.inflate(R.layout.fragment_tournament, container, false);
circle = unlimitePlayView.findViewById(R.id.circle);
circle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
xStart = (int) circle.getX();
yStart = (int) circle.getY();
xRand = new Random().nextInt(deviceWidth - circle.getWidth());
yRand = new Random().nextInt(deviceHeight - circle.getHeight());
Path path = new Path();
path.moveTo(xStart, yStart);
path.lineTo(xRand, yRand);
animCircle = ObjectAnimator.ofFloat(circle, "x", "y", path);
animCircle.setDuration(1000);
animCircle.start();
animCircle.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float currentX = (float) valueAnimator.getAnimatedValue("x");
float currentY = (float) valueAnimator.getAnimatedValue("y");
int currentLength = (int) Math.sqrt(Math.pow(Math.abs(currentX - xStart), 2) + Math.pow(Math.abs(currentY - yStart), 2));
if (currentLength > MAX_LENGTH) {
Toast.makeText(getActivity(), "DONE", Toast.LENGTH_SHORT).show();
}
}
}
}
}
}

写得好!这是因为currentLength > MAX_LENGTH不仅第一次是正确的。如果一次为真,那么onAnimationUpdate()的每次调用都为真。

记住吐司是在之前展示的,然后防止它。例如:

animCircle.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
private boolean wasFired = false;

@Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
float currentX = (float) valueAnimator.getAnimatedValue("x");
float currentY = (float) valueAnimator.getAnimatedValue("y");
int currentLength = (int) Math.sqrt(Math.pow(currentX - xStart, 2) + Math.pow(currentY - yStart, 2));
if (currentLength > MAX_LENGTH && !wasFired) {
Toast.makeText(getActivity(), "DONE", Toast.LENGTH_SHORT).show();
wasFired = true;
}
}
}

另一个小改进:我删除了abs(),因为负数的平方总是正的。

相关内容

  • 没有找到相关文章

最新更新