Saturday, June 11, 2011

Android TableLayout and expanding TextView

Many forms I am used to seeing have the following layout

Label     Input
Label     Input
...

Label     Input
 Save Button

To implement this in android I used a TableLayout inside a ScrollView. Inside the TableLayout I have TextViews and EditTexts. I wanted the EditTexts to take most of the width, so I put android:stretchColumns="1" inside the TableLayout tag. Everything looked fine until I entered a long text. I just couldn't see it. The text is not wrapped and no multi lines appear. It appears that the same column I marked for stretching should be marked for shrinking. So adding  android:shrinkColumns="1" solved my problem. And then I found the explanation in android docs (of course!): 
 If marked as shrinkable, the column width can be shrunk to fit the table into its parent object. If marked as stretchable, it can expand in width to fit any extra space. The total width of the table is defined by its parent container. It is important to remember that a column can be both shrinkable and stretchable. In such a situation, the column will change its size to always use up the available space, but never more. 
Here is the layout:

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="fill_parent"
            android:layout_width="fill_parent">
    <TableLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:stretchColumns="1" 
             android:shrinkColumns="1"
            android:padding="3dip">
        <TableRow>
            <TextView android:text="@string/first_name"
                      android:padding="3dip"/>
            <EditText android:id="@+id/first_name" />
        <TableRow>

        <TableRow>
            <TextView android:text="@string/last_name"
                      android:padding="3dip"/>
            <EditText android:id="@+id/last_name" />
        </TableRow>

        <View android:layout_height="2dip"
              android:background="#FF909090"
              android:layout_marginBottom="3dip"/>

        <Button android:id="@+id/save"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:text="@string/save_btn"
                android:onClick="save"/>

    </TableLayout>
</ScrollView>


No comments:

Post a Comment