Skip to content Skip to sidebar Skip to footer

Getheight() Of Layout Returns Zero By Viewtreeobserver

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 call

Solution 1:

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);
}

Solution 2:

I have encountered the same issue, but reason is not the same as @aga answer. The problem is my view is hidden when activity is initialized (inside onCreate). And I just move the code that show/hide my view after the layout size calculation is completed for it to work as expected. Hope this can help.

Solution 3:

OnGlobalLayoutListener is work on ViewTreeObserver, and its method onGlobalLayout does not called immediately. This Listener only works on some event occurred in current layout (when some changes is shown to the listener). so, you get 0 height when you load your layout.

if you want to access this value outside ViewTreeObserver the solution is this:

privateint height;

ViewTreeObserverviewTreeObserver= toolbar.getViewTreeObserver();
viewTreeObserver.addOnGlobalLayoutListener(newViewTreeObserver.OnGlobalLayoutListener() {
    @OverridepublicvoidonGlobalLayout() {
        height = toolbar.getMeasuredHeight();
        setHeight(height);
        // Ensure you call it only once :
        toolbar.getViewTreeObserver().removeOnGlobalLayoutListener(this);
    }
});

privatevoidsetHeight(int h) {
    this.height = h;
    Toast.makeText(getApplicationContext(), String.valueOf(height), Toast.LENGTH_SHORT).show();
}

Post a Comment for "Getheight() Of Layout Returns Zero By Viewtreeobserver"