0

For example, this is mButton:

<Button
   android:id="@+id/mbtn"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="mButton" />

This is how I tried to get the height:

int height = mButton.getLayoutParams.height;

But when I logged it, it says the height is -2. I think this might be the int value of "wrap_content". So how can I get the actual height? Thx!

nomnom
  • 1,560
  • 5
  • 17
  • 31

3 Answers3

2

If you want to get the width or height of a view in activty you can get in this method..

yourview.getHeight(); 

returns zero(0) after initialization of the button because after adding it to the window only it has a width..in the below method you can height and width of a view..

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    yourview.getHeight();
    yourview.getWidth();
}
kalyan pvs
  • 14,486
  • 4
  • 41
  • 59
0

After layout has happened call View.getHeight():

public final int getHeight()

Return the height of your view.

Returns
The height of your view, in pixels.

As you guessed, layoutParams.height is just the value of wrap_content in your case, which is -2. You could set layoutParams.height to a desired height, but even then it's not necessarily the height that the view will actually end up with after all layout is done.

blahdiblah
  • 33,069
  • 21
  • 98
  • 152
0

override the method onWindowFocusChanged(boolean hasFocus);

inside write your code,

@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mbtn.getHeight();
mbtn.getWidth();
}

it will give the correct result of the view dimensions.

balaji koduri
  • 1,321
  • 9
  • 25