布局的getHeight()由ViewTreeObserver返回零

Pus*_*dra 2 android

我在OnCreate方法中使用ViewTreeObserver来获取我的工具栏和底部布局的高度,但我仍然得到0高度,为什么?难道我做错了什么?

这是我打电话的方式:

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();
Run Code Online (Sandbox Code Playgroud)

aga*_*aga 14

看起来您的布局必须进行多个度量/布局传递,并且在第一次传递后,这些布局具有零维度.尝试OnGlobalLayoutListener仅在具有正尺寸时移除.像这样的东西:

if (linearLayout.getMeasuredHeight() > 0) {
    linearLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
Run Code Online (Sandbox Code Playgroud)