androidtextviewandroid-wrap-content

Android text view wrap to max of 2 lines


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:

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.)


Solution

  • I finally found a way to do this in compose using
    modifier = Modifier.width(IntrinsicSize.Min)

    Combined with a lineLimit, this asks the view to draw "as narrow as possible", which forces the text to use 2 lines