Reputation: 1638
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!
Upvotes: 0
Views: 831
Reputation: 1321
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.
Upvotes: 0
Reputation: 14590
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();
}
Upvotes: 2
Reputation: 33991
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.
Upvotes: 0