I'm dynamically creating buttons and I want to place them randomly on the screen. In order to do that, I'm substracting the width of the button from the screen's width. The thing is, the function button.getWidth() always return 0.
I saw in other posts that people recommended using
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
placeButtonsOnScreen();
}
But even when I'm using it, it doesn't work.
private void placeButtonsOnScreen() {
Random r = new Random();
LinearLayout layout = (LinearLayout) findViewById(R.id.ordered_buttons_layout);
for (int i = 0; i < NUMBER_OF_BUTTONS; i++) {
Button hiddenButton = buttonsArr[i];
// Get random horizontal margin for the button
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
horizontalMargin = r
.nextInt(SCREEN_WIDTH - hiddenButton.getWidth());
layoutParams.setMargins(horizontalMargin, 50, 0, 0);
// Add the button to the screen
layout.addView(hiddenButton, layoutParams);
Log.d("button width",String.valueOf(hiddenButton.getWidth()));
}
}
Any ideas how can I position the buttons on the screen minus their width? Cos right now they get cut off from intersection with the right side of the screen.