【问题标题】:Randomized button sometimes overlap each other随机按钮有时会相互重叠
【发布时间】:2017-07-12 16:18:17
【问题描述】:

在我的一个按钮的 OnClick 方法中,我正在随机化它在屏幕上的位置... 它工作得很好,但是当我使用 2 或 3 个按钮来随机化它们的位置时,它们有时会相互重叠,例如一个按钮与另一个按钮有一半重叠...

这里是按钮随机位置的方法 -

private void moveButton()
    {
        if(!canMove){ return; }

        runOnUiThread(
                new Runnable()
                {
                    @Override
                    public void run()
                    {

                        Display display = getWindowManager().getDefaultDisplay();
                        Point size = new Point();
                        display.getSize(size);
                        int width = size.x;
                        int height = size.y;

                        Button button = (Button)findViewById(R.id.button);
                        Random r = new Random();

                        int startX = width/2;
                        int startY = height/2;

                        if(myscores==0){
                            button.setX(startX);
                            button.setY(startY);
                        }

                        else {

                            int x = r.nextInt(width - 210);
                            int y = r.nextInt(height - 200);

                            button.setX(x);
                            button.setY(y);
                        }
                    }
                }
        );

    }

任何帮助都将受到高度赞赏:)

【问题讨论】:

    标签: android android-layout android-button


    【解决方案1】:

    您需要检查按钮是否与另一个按钮重叠,如果重叠则再次移动:

    int x = r.nextInt(width - 210);
    int y = r.nextInt(height - 200);
    
    if (x < other.getX() + other.getWidth()
         && x + button.getWidth() > other.getX()
         && y < other.getY() + other.getHeight()
         && y + button.getHeight() > other.getY()) {
    
       moveButton();
       return;
    }
    
    button.setX(x);
    button.setY(y);
    

    【讨论】:

    • 这里的“其他”是指另一个按钮,对吧? :)
    • 非常感谢 :) 像魅力一样工作:D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-06
    • 1970-01-01
    • 2014-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多