Android - 将高度设置为TextView动态

问题描述:

我有一些与TextView高度有关的关键问题。我想根据运行时设置的内容设置TextView的高度。这里是我的XML代码: -Android - 将高度设置为TextView动态

<TextView android:id="@+id/tv" 
      android:layout_width="fill_parent" android:layout_height="wrap_content"/>` 

这里是Java代码来设置TextView的高度:

TextView tv = (TextView) findViewById(R.id.tv); 
tv.invalidate(); 
int height_in_pixels = tv.getLineCount() * tv.getLineHeight(); 
tv.setHeight(height_in_pixels); 

但问题是,它仅显示1行,并没有其余线。

在Java代码:

TextView的TV =(TextView的)findViewById(R.id.tv);

tv.invalidate(); 

int height_in_pixels = tv.getLineCount() * tv.getLineHeight(); 

tv.setHeight(height_in_pixels); 

这些线是在Java代码不需要的。在xml本身中,您提到了layout_height="wrap_content"。那么为什么你再次设置TextView的高度。并确保android:singleLine="false"<textview>。如果您没有设置任何内容,则其默认值为false。

+0

我试过这个,但它不起作用。 – RATTLESNAKE 2010-09-07 12:28:55

+0

@RATTLESNAKE:然后问题在你的输入:))。你能在你的问题上发布你的截图吗? – Praveen 2010-09-07 12:45:13

但问题是;它只显示 1行,而不显示其余行。

我认为最好的解决方案是在“ScrollView”中定义你的textview。

例如:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    > 

    <ScrollView 
     android:id="@+id/ScrollView01" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"> 

    <TextView 
      android:text="@+id/TextView01" 
      android:id="@+id/TextView01" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"> 
    </TextView> 
    </ScrollView> 

</LinearLayout>