Search code examples
androidimagetablelayout

insert an image in a tablelayout without stretching it Android


I'm having some trouble getting pictures inside a tablelayout...actually, each I have 2 columns and when i put a picture in a cell of the table, it's completely stretched and disproportionnated...I can't find how to make it stay it's original inside the cell and let the rest of the space filled by white background for instance.... XML is like that:

<TableLayout android:layout_width="fill_parent" android:stretchColumns="*"
android:layout_marginLeft="3dip" android:layout_marginRight="10dip"
android:layout_height="wrap_content">

<TableRow android:layout_marginBottom="10dip">
<TextView android:id="@+id/tv01" android:text="text1"
 android:textSize="14sp" android:layout_margin="1dip"
 android:layout_height="wrap_content" android:textColor="@color/bleuLink"
 android:layout_width="wrap_content" android:layout_weight="1"
 android:background="@color/background"></TextView>

 <Button android:id="@+id/add" android:background="@drawable/addressbook"
  android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
 <Button android:id="@+id/call" android:background="@drawable/greenphone"
  android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>


Solution

  • Your images are stretching because of this line of code.

    <TableLayout android:layout_width="fill_parent" android:stretchColumns="*" />
    

    Because you tell your table to fill its parent and then set stretchable columns to all, your layout forces its children to fill the required space. Remove the stretchable columns attribute or set it to a comma delineated list of indexes for the columns you want to stretch.

       <TableLayout android:layout_width="fill_parent"
            android:stretchColumns="0, 2" android:layout_marginLeft="3dip"
            android:layout_marginRight="10dip" android:layout_height="wrap_content">
            <TableRow android:layout_marginBottom="10dip">
                <TextView android:id="@+id/tv01" android:text="text1"
                    android:textSize="14sp" android:layout_margin="1dip"
                    android:layout_height="wrap_content" 
                    android:layout_width="wrap_content" android:layout_weight="1"></TextView>
    
                <Button android:id="@+id/add" android:background="@drawable/icon"
                    android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
                <Button android:id="@+id/call" android:background="@drawable/icon"
                    android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
            </TableRow>
        </TableLayout>
    

    Try the code above as an example.