在运行时获取膨胀的Linearlayout的高度

时间:2012-01-12 09:36:32

标签: android layout size

我正在尝试计算线性布局充气后的高度。但是,每次返回的大小为零。我在这里做错了吗?

代码如下:

LayoutInflater layoutInflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mObjectActionsBar = (LinearLayout) layoutInflater
            .inflate(R.layout.object_actions_bar, null);
    mToolbarHeight = (float) mObjectActionsBar.getHeight();
    mObjectActionsBar.setVisibility(View.GONE);
    mWorkbenchFrame.addView(mObjectActionsBar);

请帮我弄清问题是什么。

1 个答案:

答案 0 :(得分:2)

您无法计算任何视图的高度,除非它在屏幕上绘制,因此在这种情况下您需要使用观察者:

LayoutInflater layoutInflater = (LayoutInflater) getActivity()
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mObjectActionsBar = (LinearLayout) layoutInflater
            .inflate(R.layout.object_actions_bar, null);
ViewTreeObserver observer = mObjectActionsBar .getViewTreeObserver();
observer.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        //in here, place the code that requires you to know the dimensions.
         mToolbarHeight = (float) mObjectActionsBar.getHeight();
        //this will be called as the layout is finished, prior to displaying.
    }
}

mObjectActionsBar.setVisibility(View.GONE);
mWorkbenchFrame.addView(mObjectActionsBar);