2014-08-27 70 views
0

我希望TextView高度自動重新計算,具體取決於它包含多少文本。Android - 自動縮放TextView高度取決於文本

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@color/red" 
    android:gravity="center" 
    android:text="COOK COMMENT" 
    android:textAppearance="?android:attr/textAppearanceMedium" 
    android:textColor="@color/white" /> 

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_marginTop="5dp" 
    android:background="@color/white" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/textView2" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_marginLeft="10dp" 
     android:layout_marginRight="10dp" 
     android:layout_marginTop="5dp" 
     android:text="@string/longtext" 
     android:textColor="@color/black" /> 
</LinearLayout> 

</LinearLayout> 

例如,當textView2應該比linearLayout自動縮放高度應該改變它。

回答

1

使用android:layout_height="wrap_content"並確保將您的TextView嵌套在ScrollView之內。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" 
android:orientation="vertical" > 

<TextView 
    android:id="@+id/textView1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:background="@color/red" 
    android:gravity="center" 
    android:text="COOK COMMENT" 
    android:textAppearance="?android:attr/textAppearanceMedium" 
    android:textColor="@color/white" /> 

<ScrollView 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_marginTop="5dp" 
    android:background="@color/white" 
    android:orientation="vertical" > 

    <TextView 
     android:id="@+id/textView2" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:layout_marginLeft="10dp" 
     android:layout_marginRight="10dp" 
     android:layout_marginTop="5dp" 
     android:text="@string/longtext" 
     android:textColor="@color/black" /> 
</ScrollView> 

</LinearLayout> 
+0

問題是我在第一個佈局有一個滾動視圖,並且我有一個ViewPager(github.com/astuetz/ViewPagerExtensions)。我想設置它的viewPager發佈的佈局,並滾動第一個佈局(沒有發佈一個),所以我需要一個TextView,根據文本長度改變它的高度。 – ninjaxelite 2014-08-27 17:04:08

0

下面的代碼添加到控制視圖的活動:

textView2.setOnEditorActionListener(new OnEditorActionListener() { 
     @Override 
     public boolean onEditorAction(TextView v, int actionId, KeyEvent event) { 
      v.setLines(v.getLineCount()); 
      return true; 
     } 
    }); 

您還可以自定義代碼來設置以行爲單位的最小或最大高度。