2014-08-27 69 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; 
     } 
    }); 

您还可以自定义代码来设置以行为单位的最小或最大高度。