0

I am trying to calculate the height of a linear layout after it is being inflated. However, every time the size returned is zero. Am I doing something wrong here?

The code is given below:

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

Please help me in figuring out what the problem is here.

Vivek
  • 680
  • 1
  • 12
  • 24
  • Missed to mention these. mWorkbenchFrame is a FrameLayout. This code is in the onCreateView of a Fragment class. – Vivek Jan 12 '12 at 09:39
  • http://stackoverflow.com/questions/4142090/how-do-you-to-retrieve-dimensions-of-a-view-getheight-and-getwidth-always-r/4406090#4406090 – Okan Kocyigit Jan 12 '12 at 09:50

1 Answers1

2

You can not calculate height of any view, unless it is drawn on the screen, so you need to use observer in this case:

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);
jeet
  • 29,001
  • 6
  • 52
  • 53