随机按钮有时会相互重叠

时间:2017-07-12 16:18:18

标签: android android-layout android-button

在我的一个Button的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);
                        }
                    }
                }
        );

    }

任何帮助都会得到高度赞赏:)

1 个答案:

答案 0 :(得分: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);