一个文本视图,其中的字符串最多包装一行

时间:2018-10-05 11:01:54

标签: android textview

我有一个TextView,如果文本太长,我希望文字最多能绕1行。
我尝试过:

android:minLines="1"  
android:maxLines="2"  

但是这些仅在文本具有实际的新行时才起作用。
如果我使用:

android:lines="2"  

它可以工作,但是当文本中没有几个字符时,textview仍会占用两行空间。
有办法解决吗?

3 个答案:

答案 0 :(得分:1)

如果要使用maxLines参数,Textview必须具有宽度。 试试这个也许可行:

 android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:minWidth="50dp"
    android:maxLines="1"

如果Textview的父级具有最大或恒定大小,也可以使用android:maxLength

根据评论进行编辑: 在运行时设置TextView宽度

String myString = "test";
    textView.measure(0, 0);
    View parent = (View) textView.getParent();
    parent.measure(0, 0);
    int currentWidth = textView.getWidth();
    int maxAvailableWidth = parent.getWidth();
    int finalWidth = (int) (myString.length() * textView.getTextSize() * factor); // factor is depends on your typeface
    if(finalWidth > maxAvailableWidth)
        finalWidth = maxAvailableWidth;
    textView.setWidth(finalWidth);

谢谢

答案 1 :(得分:0)

尝试:

    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:ellipsize="end"
    android:maxLines="1"

答案 2 :(得分:0)

我已经在我的代码中尝试过了,并且有效。您只需要使用maxlines并将宽度设置为match_parent

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:maxLines="2"/>

输出:

enter image description here