如何动态设置textview高度android
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3522224/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to dynamically set textview height android
提问by neha
In my application I need to set dynamic text to my textview so I want it to get resized dynamically. I have set:
在我的应用程序中,我需要为我的 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"
/>
My textview height is not going beyond 2 lines and the text is getting cut. Can anybody please help?
我的 textview 高度不会超过 2 行,并且文本正在被剪切。有人可以帮忙吗?
Thanx in advance.
提前谢谢。
回答by Aaron C
As Konstantin said, this code will probably be ignored after you exceed 4 lines unless you remove android:maxLines="4"
正如康斯坦丁所说,除非您删除,否则超过 4 行后,此代码可能会被忽略 android:maxLines="4"
This is how you would set the height in code:
这是您在代码中设置高度的方式:
TextView tv = (TextView) findViewById(R.id.TextView02);
int height_in_pixels = tv.getLineCount() * tv.getLineHeight(); //approx height text
tv.setHeight(height_in_pixels);
If you want to use dip units, which allows your app to scale across multiple screen sizes, you would multiply the pixel count by the value returned by getResources().getDisplayMetrics().density;
如果您想使用倾角单位,它允许您的应用程序跨多个屏幕尺寸进行缩放,您可以将像素数乘以返回的值 getResources().getDisplayMetrics().density;
This depends on your desired behavior, but you might also consider having the TextView size fixed, and allowing the user to scroll the text:
这取决于您想要的行为,但您也可以考虑固定 TextView 大小,并允许用户滚动文本:
TextView tv = (TextView)findViewById(R.id.TextView02);
tv.setMovementMethod(ScrollingMovementMethod.getInstance());
回答by AnilPatel
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.
回答by Konstantin Burov
Remove android:maxLines="4", it restricts height of your view to 4 lines of text.
删除 android:maxLines="4",它将视图的高度限制为 4 行文本。