0

In my app I am displaying a table where the individual cells are editable text fields (i.e. EditText objects). I am currently struggling calculating appropriate widths for these.

If I set the width to be as many "Ems" as the displayed text has characters, my fields are much to wide by about a factor of 2 and the table looks ugly and wastes lots of precious screen space. Setting the width in "Ems" is essentially like assuming the worst case, i.e. the width of a string under the assumption that it contains only the broadest characters in a font, usually 'M' (hence the name of the method), 'm', 'W', or '_'). But on average strings contain narrower characters and so most of these fields are half empty and much too wide for their actual content. I am thus desperately seeking a way to calculate a better fitting width, not that worst case width.

The "normal" way to do this in Java (in AWT or Swing at least) is to asks a widget's current Font (actually a Font's FontMetrics), to calculate and return the width that will be necessary to display a given string in pixels. But how does one obtain a TextView's Font? I haven't found any method to obtain a (Text)View's font and/or calculate a more appropriate width given the actual content of a cell's text string. How does one do that in Android?

Michael

1 Answer 1

5

I just found the "missing link": <TextView>.getPaint() is the answer!

The "Paint" then has methods like <Paint>.measureText(...) to calculate a string's width and <Paint>.ascent() and <Paint>.descent() to calculate a string's height.

Michael

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.