0

how to get button size, after taking into consideration wrap_content attribute?

I want to create 2 buttons of equal sizes, both of them with wrap_content attribute, so my solution was to create them both with wrap_content, get the maximum width and height, and apply the max values to the two buttons, the problem is that I am getting only zeros values when trying to print the width and height of the button.

//Create the first button
    Button firstButton= new Button(activity);
    LinearLayout.LayoutParams secondaryParams = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
    footerLayout.addView(firstButton, firstParams);

//same thing for the other button
   Button secondaryButton= new Button(activity);
    LinearLayout.LayoutParams secondaryParams = new LinearLayout.LayoutParams(
                            LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1f);
    footerLayout.addView(secondaryButton, 0, secondaryParams );


//trying to get the size:
  firstButton.measure(0, 0); //must call measure!
    int measuredWidth = firstButton.getWidth();
    int measuredHeight = firstButton.getHeight();

get the size of the 2 buttons, after the WRAP_CONTENT attribute has been applied.

1 Answers1

1

You are trying to get the width and height too early, actually, if you are using an activity you can get the dimensions here:

@Override
 public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  //Here you can get the size!
 }

This method gets called multiple time or every time when there's a change(View hide, gone, adding new views, etc..) in the window. So use it carefully!

Jagar
  • 777
  • 9
  • 24
  • I am using the generic Activity, a lot of other code depend on that, I don't want to create an extended activity just for this purpose, can you think of other things to try? – Liran Siman Tov Sep 19 '19 at 14:33
  • check one of these solutions https://stackoverflow.com/a/24035591/12053756 – Jagar Sep 19 '19 at 14:37