android - Best practice for getting View dimensions, possibly before they are drawn to screen -
i've seen ton of different questions , answers problems people having retrieving height , width of views, particularly this thread.
the following mentioned methods retrieve view dimensions:
- onwindowfocuschanged() in activity
- subclassing type of view you're using , overridding either onsizechanged(), onlayout(), or onmeasure()
- using viewtreeobserver , addongloballayoutlistener()
each of them seem work in cases, while in other cases people doesn't work correctly. since there isn't setondimensionsknown(ondimensionsknown odk) or similar method view class, of these methods (or possibly 1 not mentioned) give me dimensions view have, regardless if it's drawn yet, has wrap_content or fill_parent parameters, or has explicit height , width set in px, dp, or similar?
edit: perhaps specific example helpful, i'm trying make popupwindow wrap it's contents, , offset in -x direction value of it's width. problem contents width, , popupwindows width, not measured until after show popup. can't think of way measure width before drawn screen.
my usual approach override whatever view class need dimensions of before being drawn, , create own setondimensionsknown(ondimensionsknown odk) method , fire width , height values onmeasure called with. works every case i've needed, doesn't seem elegant override every view class this.
i can post code explain example more.
good way of doing adding ongloballayoutlistener()
view, stated in this answer (point 3 in question, in opinion that's reliable view
). way popupwindow
inflate it's layout , 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 parent's layout (not sure if correct values, measures okay in case)
and numbers calling popupview.getmeasuredheight()
, .getmeasuredwitdh()
.
your problem long gone now, else stumble upon , find helpful. :)
Comments
Post a Comment