简体   繁体   中英

Android: set button to random position

How can I as easy as possible set the position of my Button to a random place?
I've tryed to use this: (My screen resolution is 800x480)

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

int x = r.nextInt(480);
int y = r.nextInt(800);

btn.setX(x);  
btn.setY(y);

But when i use this, it seems that the button some times get located outside my application or so? is it possible to prevent this and keep the button inside the app?

Pretty sure your problem is you are not accounting for the width and height of the button, and so if it randoms to 480*800 it will be off the screen. Try something similar to:

int x = r.nextInt(480 - buttonWidth);
int y = r.nextInt(800 - buttonHeight);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM