如何在Android中动态设置TextView的高度

13

在我的应用程序中,我需要将动态文本设置到我的TextView中,所以我希望它可以根据内容自动调整大小。我已经设置了:

<TextView
android:id="@+id/TextView02" 
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="normal"
android:text="Frontview"
android:layout_weight="1"
android:gravity="center_vertical"
android:textColor="#0099CC"
android:singleLine="false"
android:maxLines="4"
android:ellipsize="marquee"
/>

我的textview高度不能超过两行,文本被截断了。

3个回答

19

正如Konstantin所说,在超过4行后,除非您删除android:maxLines="4",否则此代码可能会被忽略。

以下是在代码中设置高度的方法:

TextView tv = (TextView) findViewById(R.id.TextView02);
int height_in_pixels = tv.getLineCount() * tv.getLineHeight(); //approx height text
tv.setHeight(height_in_pixels);

如果要使用dip单位,使应用程序在多个屏幕尺寸上具有可伸缩性,则应将像素数乘以由getResources().getDisplayMetrics().density;返回的值。

这取决于您的期望行为,但您还可以考虑固定TextView大小,并允许用户滚动文本:

TextView tv = (TextView)findViewById(R.id.TextView02);
tv.setMovementMethod(ScrollingMovementMethod.getInstance());

如何获取height_in_pixels的动态值? - neha
我编辑了我的答案以获取文本的大致高度。您可能需要添加一个小缓冲区,以便挂在行下方的字符不会被切断(如“g”、“y”等)。 - Aaron C
感谢Aaron C,但在设置文本高度后,该文本已经消失了。尽管tv不为空,但高度被设置为0。 - neha
如果文本尚未渲染,getLineCount() 将返回 0。您可以调用 invalidate() 强制重新绘制,但 setText() 应足以使 getLineCount() 有效。 - Aaron C

3
TextView tv;
----------------------
tv=new TextView(this);   // you take TextView id (R.id.textview1)

LinearLayout.LayoutParams Params1 = new LinearLayout.LayoutParams(15,50);
tv.setLayoutParams(Params1);   //you take linearlayout and relativelayout.

0

移除 android:maxLines="4",它会限制你的视图高度为4行文本。


我的TextView高度不超过2行,文本被截断了。 - neha

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