Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getHeight() of layout returns zero by ViewTreeObserver

Tags:

android

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();
like image 496
Pushpendra Avatar asked Dec 01 '22 17:12

Pushpendra


1 Answers

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);
}
like image 172
aga Avatar answered Dec 04 '22 12:12

aga