Kent P
Kent P

Reputation: 43

Android: How do I randomly place an array of buttons in an activity?

I was wondering how I could "randomly" place an array of Buttons in a RelativeLayout?

Is it possible to space the buttons around the entire view?

Thanks for your help! I tried using setX() and setY() but they are float numbers and I'm unsure how they place the buttons in proportion to the size of the screen.

Upvotes: 2

Views: 1606

Answers (2)

You can add layout margins to your buttons. As margins will be interpreted not relative to each other but to the frame, it will in fact position your buttons.

To set the margins you have to set the view's layout params:

RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
Random random = new Random();
params.leftMargin = random.nextInt(100);
params.topMargin = random.nextInt(100);
button.setLayoutParams(params);

However this may cause your buttons to overlap, or be outside the Activity, so it's best not to use entirely random values for positions but to perform checks for overlapping and set random ranges according to the device resolution and button size.

To get device display size:

Display display= activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int Height = display.getHeight();

Upvotes: 3

karan
karan

Reputation: 8853

instead do something like this first create a button array and find the respective id...

LayoutParams lp = new LinearLayout.LayoutParams(widthOfButtons,LayoutParams.WRAP_CONTENT);
Button[] buttons; 
for(int i=0; i<4; i++) {  //suppose you have four buttons
{
 String buttonID = "button" + (i+1);
 int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
 buttons[i] = ((Button) findViewById(resID));
 buttons[i].setHeight(yourvalue);
 buttons[i].setWidth(yourvalue);
 buttons[i].setLayoutParams(lp);
}

hope it works for your

Upvotes: 0

Related Questions