I am using ViewTreeObserver in OnCreate method to get height of my toolbar and bottom layout but still I am getting 0 height, why? Am I doing something wrong?
This is how I am calling:
ViewTreeObserver viewTreeObserver = toolbar.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
// Ensure you call it only once :
toolbar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
height1 = toolbar.getMeasuredHeight();
}
});
final LinearLayout linearLayout = (LinearLayout) findViewById(R.id.bottom);
ViewTreeObserver vto = linearLayout.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onGlobalLayout() {
// Ensure you call it only once :
linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
height2 = linearLayout.getMeasuredHeight();
}
});
Toast.makeText(getApplicationContext(), String.valueOf(height1) + String.valueOf(height2), Toast.LENGTH_SHORT).show();
Looks like your layout has to make more than one measure/layout pass, and the pieces of layout have zero dimensions after the first pass. Try to remove OnGlobalLayoutListener
only when you have positive dimensions. Something like this:
if (linearLayout.getMeasuredHeight() > 0) {
linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With