gpt4 book ai didi

android - 字符串最多换行的 TextView

转载 作者:行者123 更新时间:2023-11-29 23:30:59 25 4
gpt4 key购买 nike

我有一个 TextView,如果文本太长,我希望它最多环绕 1 行。
我试过了:

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

但这些仅在文本有实际换行时才有效。
如果我使用:

android:lines="2"  

它可以工作,但是当文本中的字符很少时,textview 仍然占用 2 行的空间。
有办法解决这个问题吗?

最佳答案

如果你想使用 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);

谢谢

关于android - 字符串最多换行的 TextView ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52664168/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com