I have built a ListView and my items - at least in part - contain titles of various (text) lengths. In order to enable the user to read as much of the title as possible, I'm trying to change my adapter to auto-pi开发者_如何学运维ck a feasible font size for my texts.
So I'm working with the TextView's paint object to measure the text in a basline font size (14dp) and try to compare against the available space. If the text is too big, I reduce the font size to 12dp (later I might think about reducing it even further).
// Note: vh.filmTitleTextView is my TextView, filmText contains the title I want to display
filmTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14);
float textWidth = vh.filmTitleTextView.getPaint().measureText(filmText);
if (textWidth > vh.filmTitleTextView.getWidth())
vh.filmTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 12);
The issue is that on first run, vh.filmTitleTextView.getWidth() always returns zero. I guess this is because the layout has not been rendered before and the size is not yet known.
I can't just go with the full size of the ListView because the textView doesn't have the same width (despite the fact that it is set to layout_width="fill_parent") - there are some elements around it.
Any ideas?
Had a similar problem that was my bane for a long time - this might help ya: Auto Scale TextView Text to Fit within Bounds
精彩评论