【问题标题】:How to move button randomly on the screen on click?单击时如何在屏幕上随机移动按钮?
【发布时间】:2014-06-21 23:56:04
【问题描述】:

所以我试图让屏幕上的按钮在被点击时移动。它目前设置为计算点击次数,但我希望按钮在您每次点击时移动。我尝试了一个翻译动画,但它不起作用,因为该按钮仍会从原始位置触发 onClick。

我了解了 ObjectAnimator 并一直试图让它工作,因为 onClick 事件将随着按钮移动,但我似乎无法让它工作。我还需要帮助让按钮在其布局父级中随机移动。任何帮助将不胜感激:)

这是我当前的 Object Animator 代码。请注意,它尚未设置为随机移动,因为我不确定如何让它做到这一点:

ObjectAnimator  animX = ObjectAnimator.ofFloat(btnCount, "xTranslate", 0f, 50f);
                    ObjectAnimator animY = ObjectAnimator.ofFloat(btnCount, "TranslateY", 0f, 50f);

                       AnimatorSet animSet = new AnimatorSet();
                       animSet.playSequentially(animX, animY);
                       animSet.setDuration(500);


                   animSet.start();

【问题讨论】:

    标签: android animation button random move


    【解决方案1】:

    完成此操作的最简单方法如下所示。在您的 onClick 监听器上执行此操作。

    btnCount.animate().xBy(10).yBy(10);
    

    关于随机,我想你可以使用像这样简单的东西......无论如何,你可能必须注意达到屏幕限制。

    Random r = new Random();
    btnCount.animate().xBy(r.nextInt(10)+1).yBy(r.nextInt(10)+1);
    

    【讨论】:

    • 但是您提供的代码不会为按钮设置动画。这是你想要的吗?
    • 是的,只是想弄清楚如何将按钮移动到新位置。我不必看到按钮实际移动,只需从一个位置移动到屏幕上的随机位置。
    • 什么是按钮数?
    【解决方案2】:

    发现使用以下内容可以满足我的需要:

    Random r = new Random();
                            int buttonHeight;
                            int buttonWidth;
                            buttonHeight = btnCount.getHeight();
                            buttonWidth = btnCount.getWidth();
                            int xLeft = r.nextInt(480 - buttonHeight);
                            int yUp = r.nextInt(800 - buttonWidth);
                            int xRight = r.nextInt(480 + buttonHeight);
                            int yDown = r.nextInt(800 + buttonHeight);
    
                            btnCount.setX(xLeft);       
                            btnCount.setY(yUp);
                            btnCount.setX(xRight);
                            btnCount.setY(yDown);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多