0

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.

itaied
  • 6,827
  • 13
  • 51
  • 86
  • Not sure but your code implies the button is hidden, if so then it would not have a width because it is not drawn. Try calling measure() then getMeasuredWidth(). – Larry McKenzie May 21 '14 at 18:15
  • A good answer on pre-measuring views here: http://stackoverflow.com/a/8403680/278385 – jqpubliq May 21 '14 at 18:29

2 Answers2

1
myView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            myView.getViewTreeObserver().removeGlobalOnLayoutListener(this);

           placeButtonsOnScreen();
        }
    });
Santosh Kathait
  • 1,444
  • 1
  • 11
  • 22
0

You should use RelativeLayouts and make buttons position according to each other (Aligning of course the one closest to the right side of the screen as alignedToParentRight = true)

Mouhamed Ndiaye
  • 1,390
  • 2
  • 13
  • 21