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.
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!