在TextView中,当单词的长度大于宽度可容纳的长度时,它会包装文本并将其移动到下一行。但是,即使右侧有空白,TextView也不会包装自己的宽度。
如何在TextView包装文本时使TextView减小宽度?
这是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" />
并且,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>
答案 0 :(得分:0)
正如您在例子中看到的那样,当有新行(\n
)分隔内容时,TextView可以完美地包装其内容。
所以解决方案很简单,计算新行的位置并将它们插入String!
我使用方法measureText
来计算当前文本的宽度。如果它小于最大宽度我尝试在线上添加更多文本。当它达到maxWidth时,插入一个新行!
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;
}