带滚动条和最大高度限制的Android TextView

25
我需要设置TextView的最大高度(使用maxHeight或maxLines)。如果有更多的文本行,应该显示滚动条。我应该使用什么标记来实现这个功能?
最初的想法是使用ScrollView包装TextView,但ScrollView没有maxHeight属性。
1个回答

66

页面布局:

<TextView
    android:id="@+id/text_view"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:singleLine="false"
    android:maxLines="3"
    android:scrollbars="vertical"
    android:textColor="@android:color/secondary_text_dark_nodisable"
    >
</TextView>

代码:

TextView textView = (TextView)findViewById(R.id.text_view);
textView.setMovementMethod(ScrollingMovementMethod.getInstance());

注意:

android:textColor="@android:color/secondary_text_dark_nodisable" 用于避免 TextView 在被触摸时出现文本淡化。


5
当我尝试这样做时,TextView 显示滚动条,但实际上我无法使其滚动。 - quikchange
5
你需要在代码中执行以下语句:TexView.setMovementMethod(new ScrollingMovementMethod())。这将使文本视图具有滚动功能。 - Cristian
我使用了这种方法,因为我无法将超过两行的文本省略。谢谢。 - efeyc
2
@alex2k8,四年后你的回答帮了我大忙。浪费了一个小时来弄清楚这个问题。 - vforvendetta

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