Search code examples
androidtextviewheightscale

Android - Autoscale TextView height depending to text


I want that a TextView height automatically rezises depending on how much text it contains.

<?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>

When for example the textView2 should be auto scaled than the linearLayout height should change whit it.


Solution

  • Use android:layout_height="wrap_content" and make sure you nest your TextView inside a 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>