2010-09-07 130 views
0

我有一些與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行,並沒有其餘線。

回答

3

在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

但問題是;它只顯示 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>