3

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-pick 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?

Patrick
  • 33
  • 1
  • 3

1 Answers1

2

Had a similar problem that was my bane for a long time - this might help ya: Auto Scale TextView Text to Fit within Bounds

Community
  • 1
  • 1
Nathan Fig
  • 14,103
  • 9
  • 40
  • 56
  • Great :) Please mark answer as correct. You might also read the Stack Overflow FAQ - getting familiar with it and staying active is a great way to learn about whatever it is you're developing. – Nathan Fig Jul 07 '11 at 15:12
  • Small update: I found that the AutoResizeTextView class (as referenced in the article Nathan referenced) works fine from a functionality point of view, but in my case it seems to have a significant impact on the scrolling performance of my listview. I'm currently looking into why this is and am trying to find ways to improve this. – Patrick Jul 07 '11 at 20:51
  • That doesn't surprise me much- running a resizing algorithm every time the view is drawn will slow it down. Make sure you're recycling the view passed in to getView() when possible, and optimize the algorithm as best you can. – Nathan Fig Jul 11 '11 at 12:53
  • 1
    I ended up with a quickhack TextView class which memorizes the available space (width) in a static field once the first instance is drawn. From then on it calculates the text size based on that.So all rows but the first one will only be drawn once. – Patrick Jul 14 '11 at 10:41