2

I've seen a ton of different questions and answers to the problems people are having with retrieving height and width of views, particularly this thread.

The following are mentioned methods to retrieve View dimensions:

  1. onWindowFocusChanged() in your activity
  2. Subclassing the type of view you're using and overridding either onSizeChanged(), onLayout(), or onMeasure()
  3. Using a ViewTreeObserver and addOnGlobalLayoutListener()

Each of them seem to work in some cases, while in other cases people say something doesn't work correctly. Since there isn't a setOnDimensionsKnown(OnDimensionsKnown odk) or similar method for the View class, which of these methods (or possibly one not mentioned) will give me the dimensions my view will eventually have, regardless if it's drawn yet, has wrap_content or fill_parent parameters, or it has explicit height and width set in px, dp, or similar?

EDIT: Perhaps a specific example would be helpful, I'm trying to make a PopupWindow wrap it's contents, and to be offset in the -x direction by the value of it's width. The problem is that the contents width, and thus the popupwindows width, are not measured until after I show the popup. So basically I can't think of a good way to measure the width it will be before it is drawn to screen.

My usual approach is to override whatever view class I need the dimensions of before it being drawn, and create my own setOnDimensionsKnown(OnDimensionsKnown odk) method and fire it with the width and height values that onMeasure is called with. This works it every case I've needed, but it doesn't seem very elegant to override every view class to do this.

I can post code to help explain the example more.

Community
  • 1
  • 1
mpellegr
  • 3,072
  • 3
  • 22
  • 36

1 Answers1

0

Good way of doing it is adding an OnGlobalLayoutListener() to the view, as stated in this answer (point 3 in your question, in my opinion that's the most reliable for any View). The way I do it for a PopupWindow is to inflate it's layout and then call measure on it:

popupView = getActivity().getLayoutInflater().inflate(R.layout.popup_layout, null);
popup = new PopupWindow(popupView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, true);
popupView.measure(view.getMeasuredWidth(), view.getMeasuredHeight()); //the view is parent's layout (not sure if those are correct values, but it measures okay in my case)

and then just get the numbers by calling popupView.getMeasuredHeight() and .getMeasuredWitdh().

Your problem is probably long gone by now, but hopefully someone else will stumble upon this and find it helpful. :)

Community
  • 1
  • 1
Klotor
  • 181
  • 8