How to make TextView have maxLines and if it doesn't fit expand horizontally?

730 Views Asked by At

I don't want to use scrollView.The behavior I want is this:

Short Text:

enter image description here

Long text:

enter image description here

2

There are 2 best solutions below

0
On

Try this:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:text="Your text here"
    android:textColor="@color/purple_500"
    android:textStyle="bold"
    android:lines="2"
    android:gravity="center"
    android:autoSizeTextType="uniform"
    android:autoSizeMinTextSize="16sp"
    android:autoSizeMaxTextSize="100sp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

For short text your output be like:

Short Text Image

For long text:

Long Text Image

0
On

Have you tried minLines in XML?

something like this:

<TextView
        android:id="@+id/tv_previous_story"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="3dp"
        android:minLines="2" //(could be any minimum amount of lines)
        android:textColor="@color/text_color"
        android:textSize="@dimen/privacy_text_size" />

this should work fine for you if you always have at least two words (or the minimal amount of lines you've set in the XML)...

If this isn't what you search for, maybe you could handle it programmatically and set the width and height of the TextView according to the number of words... not the exact method, but for example:

void updateWidthAndHeightOfTextView(TextView tv, String t) {
   tv.setWidth(t.length * [bla bla bla]);
   tv.setHeight(tv.getWidth() / [bla bla bla]); //(if you want to change the height too, in this case according to the width)
}

You write it your way, you know your needs...

And, there's also this answer, that I'm actually not familiar with but might also answer your needs...

UPDATE

In case I didn't understand when I wrote the above and you want the TextView to have maxLines and only dynamic width, you could use the tv.setWidth(t.length * [bla bla bla]); in the semi method that I wrote above, and in the .XML use maxLines...

Also, next time please give a bit more specific questions so people won't have to struggle to try to understand how to give you the relevant answer to what you want.

I hope it helps you!