【问题标题】:How to dynamically set textview height android如何动态设置textview高度android
【发布时间】:2010-08-19 13:24:53
【问题描述】:

在我的应用程序中,我需要为我的 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 高度不超过 2 行,并且文本被剪切。 有人可以帮忙吗?

提前感谢。

【问题讨论】:

    标签: android textview


    【解决方案1】:

    正如康斯坦丁所说,这段代码在超过 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);
    

    如果您想使用允许您的应用在多个屏幕尺寸上进行缩放的倾斜单位,您可以将像素数乘以 getResources().getDisplayMetrics().density; 返回的值

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

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

    【讨论】:

    • 如何获取 height_in_pixels 的动态值?
    • 我编辑了我的答案以获得文本的大致高度。您可能需要添加一个小缓冲区,以便悬挂在行下方的字符不会被截断(“g”、“y”等)。
    • Thanx Aaron C,但文字在设置高度后消失了。尽管 tv 不为空,但高度设置为 0。
    • 如果文本尚未呈现,getLineCount() 将返回 0。您可以调用 invalidate() 来强制重绘,但 setText() 应该足以使 getLineCount() 有效。
    【解决方案2】:
    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.
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 我的 textview 高度不超过 2 行,文本被剪切。
      猜你喜欢
      • 1970-01-01
      • 2012-09-29
      • 2011-04-06
      • 1970-01-01
      • 2013-10-07
      • 2023-03-23
      • 1970-01-01
      • 2016-04-24
      • 2021-09-18
      相关资源
      最近更新 更多