While programmatically laying out views, I encountered the following issue:
Unlike TextArea
and Bitmap
, which have their width
and height
properties populated upon instantiation, a Text
drawable does not provide valid dimensions until after it has been drawn. Moreover, if the text content changes, the updated dimensions are only reflected after the next draw cycle. As far as I can tell, this behavior is undocumented and makes it difficult to perform layout calculations in advance.
I suspect the root cause is that the text width can only be calculated with access to a valid Dc
(drawing context).
Proposed Improvements
-
Introduce a
Graphics
method to calculate text width without aDc
TheGraphics
module already provides functions for retrieving font height. It would be highly beneficial to add a method likeGraphics.getTextWidth(font, text)
that returns the width of the text in pixels and works independently of aDc
. Currently, my workaround is to create a 1-pixelBufferedBitmap
just to obtain a validDc
, which feels like an unnecessary hack. I assume the SDK has more efficient means internally to determine text width without requiring a drawing context. -
Populate
Text
dimensions immediately on text updates
TheText
drawable should use this functionality to populate itswidth
andheight
properties as soon as the text is set or updated. This would allow developers to query layout-relevant dimensions immediately, without relying on post-draw state.