Friday, October 28, 2011

lining up ImageViews horizontally

I had an app that I was developing that required me to have three images lined up horizontally.  The problem is that I could not get them to line up in the center.  I could use margins and padding, but on devices of different screen sizes and pixel densities, this would not look good.  Below is the XML code that allowed me to do this and a screen shot.

 

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

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Large Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:paddingLeft="4.0dip"
        android:paddingRight="4.0dip"
        android:paddingTop="5.0dip"
        android:paddingBottom="1.0dip">


    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="0.0dip"
            android:layout_height="fill_parent"
            android:src="@drawable/ql" android:layout_weight="1.0"/>

        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="0.0dip"
            android:layout_height="fill_parent"
            android:src="@drawable/ql" android:layout_weight="1.0"/>
               
        <ImageView
            android:id="@+id/imageView1"
            android:layout_width="0.0dip"
            android:layout_height="fill_parent"
            android:src="@drawable/ql" android:layout_weight="1.0"/>               

    </LinearLayout>

</LinearLayout>

 

image

 

The key to making this work is the android:layout_weight.  The layout_weight takes any unused space in the layout and evenly distributes it among the widgets in the layout.

No comments:

Post a Comment