简体   繁体   中英

How to make a TextView reduce its width if text is wrapped and moved to next line?

In a TextView, when there the length of the word is greater than the width can accommodate, it wraps the text and moves it to the next line. However, the TextView doesn't wrap its own width even though there is empty space to the right.

How can I make the TextView reduce its width when it's wrapping the text?

TextView没有包装宽度

Here's the TextView :

<TextView
    android:id="@+id/userMessageTextView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginLeft="50dp"
    android:layout_marginRight="40dp"
    android:layout_marginTop="2dp"
    android:autoLink="web"
    android:background="@drawable/textview_design"
    android:padding="8dp"
    android:text="some text"
    android:textColor="#333333"
    android:textSize="17sp" />

And, textview_design.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="#EEEEEE" />
    <corners
        android:radius="@dimen/chat_message_text_corner_radius" />
</shape>

As you saw in your exemple, the TextView can perfectly wrap its content when there are new lines ( \\n ) to separate the content.

So the solution is simple, calculate where the new lines should be and insert them in your String !

I use the method measureText to calculate the width of the current text. If it's smaller than the max width I try to add some more text on the line. When it reaches the maxWidth, a new line is inserted !

String message = "This is a long message that will be displayed on multiple lines";
int textViewContentMaxWidth = 600; // you need to calculate that value, for me it was screenWidth - 40 dp (16dp margins on each side and 4 dp padding on each side)

String[] sections = message.split(" ");
String formattedMessage = ReplaceBreakWordByNewLines(sections, tv.getPaint(), textViewContentMaxWidth)
tv.setText(formattedMessage);

--

public static String ReplaceBreakWordByNewLines(String[] _texts, Paint _paint, int maxWidth)
{
    String formattedText = "";

    String workingText = "";
    for (String section : _texts)
    {
        String newPart = (workingText.length() > 0 ? " " : "") + section;
        workingText += newPart;

        int width = (int)_paint.measureText(workingText, 0, workingText.length());

        if (width > maxWidth)
        {
            formattedText += (formattedText.length() > 0 ? "\n" : "") + workingText.substring(0, workingText.length() - newPart.length());
            workingText = section;
        }
    }

    if (workingText.length() > 0)
        formattedText += (formattedText.length() > 0 ? "\n" : "") + workingText;

    return formattedText;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM