I'm trying to get a textview to occupy up to 2 lines (would only be 1 line if there is only 1 word / no spaces), but be as narrow as possible.
For example:
Short
Medium
Text
Some longer
text here
Some very long text that might get very
wide but will never go over 2 lines
Any ideas on how to achieve this?
At the moment, the only way I've found is to hard code line breaks in my strings, which isn't ideal, and is resulting in a lot of duplicated strings.
Added for clarification: The layout containing the text view gets used in a recylerView, so I can't (and don't want to) constrain the width - the textview should grow as large as it needs to (and hence expand it's parent, which is set to wrap_content), but do so over 2 lines not 1.
To put it another way, a textView with fixed height and variable width, to show all the content.
Extending TextView
Ok, so I think my only option is to create a custom textview. I'm new to this, so here's the approach I'm planning:
- Extend TextView and override onDraw();
- split the string by the first space encountered
- Measure widths of strings A and B
- Get max of A and B lengths
- split the string by the second space encountered (if exists)
- Get max width of 2 sub strings
- Compare to the max width from this split to the max width from the first split, and keep lowest
- Repeat this for every space in the string, to determine which split results in the smallest overall width
- Set the width of the TextView based on this
Does this make sense? Is there a better approach?
(Note, if I was using a fixed width font, I could use the string length/2, and step out either side from that until I hit a space and then replace that with a line break.)