0

I already have a method to display the button in random position of the screen but it is NOT adaptable to other screen sizes. How can I do it (inside: r.nextInt()).

int buttonHeight;
int buttonWidth;
buttonHeight = button.getHeight();
buttonWidth = button.getWidth();
int xLeft = r.nextInt(480 - buttonHeight);
int yUp = r.nextInt(500 - buttonWidth);
int xRight = r.nextInt(670 + buttonHeight);
int yDown = r.nextInt(1400 + buttonWidth);

button.setX(xLeft);
button.setY(yUp);
button.setX(xRight);
button.setY(yDown);

I just want the random number to be adaptable to every screen size.

1 Answers1

0

Android coordinates are based on the view's top left corner. So the x and y values you feed to the view are actually x and y of the view's top left corner. Try limit the nextInt()'s argument to something like, random.nextInt(maxScreenWidth - buttonWidth) and random.nextInt(maxScreenHeight-buttonHeight) and assign these coordinates to your button's x and y.

WasabiTea
  • 389
  • 2
  • 10