如何实现一个带有最大高度和内部滚动的多行 TextView

5
我想限制TextView在屏幕中所占用的空间,具体规则如下:
  • 如果文本很短(比如140个字符或2行),则让其占据需要的空间,但不要超过限定值。
  • 如果文本很长,即一段落,则限制视图的最大高度(通过maxHeight或最大行数实现)。
这里有一些截图,展示了有效和无效结果:

短文本:

enter image description here

中等长度文本:

enter image description here

内部滚动:

enter image description here

空格:

enter image description here

过长的文本:

enter image description here

2个回答

9

试试这样做。

XML

<TextView
   android:id="@+id/descTxtView"
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:maxLines="5"
   android:scrollbars="vertical"
   android:text="Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry&apos;s standard dummy text ever since the 1500s."
   android:textColor="#232e3b"
   android:typeface="sans" />

在JAVA中:
descTxtView= (TextView) findViewById(R.id.descTxtView);
descTxtView.setMovementMethod(new ScrollingMovementMethod());

谢谢您的回答,为什么要使用60dp的固定高度?我正在测试height=wrap_content,maxLines=5,并设置setMovementMethod(new ScrollingMovementMethod()),看起来好像可以工作。 - Addev
我的错误,使用了wrap_content。 - Kaushik

3

如果您想通过行数限制TextView的高度,可以使用android:maxLines属性:

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:maxLines="5"
    android:scrollbars="vertical"
    android:requiresFadingEdge="vertical" />

在您的代码中,请按照以下方式编写:
yourTextView.setMovementMethod(new ScrollingMovementMethod());

使用这段代码,当文本超出定义的maxLines时,您的TextView可以垂直滚动。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接