views:

664

answers:

2

Hi, I have this XML code which generates a button, a textview and another button, How do I go about getting the button to appear in far left, the textview in the center and the last button on the far right?

< ?xml version="1.0" encoding="utf-8"?>  

< LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android">

          <Button android:id="@+id/Button01" 
                  android:layout_width="wrap_content" 
                  android:layout_height="wrap_content" 
                  android:text="Cancel">
          </Button>
          <TextView android:id="@+id/TextView01" 
                    android:layout_width="wrap_content" 
                    android:layout_height="wrap_content" 
                    android:text="New Place">
          </TextView>
          <Button android:id="@+id/Button03" 
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content"
                  android:text="Save">
          </Button>

A: 

You need to use the weight property. Think of it as letting android know the percentage of width it should give each item.

you need to set width to 0dip for all the 3 items and add the weight property

    <Button android:id="@+id/Button01" 
              android:layout_width="wrap_content" 
              android:layout_height="wrap_content" 
              android:text="Cancel"
              android:layout_width="0dip" 
              android:layout_weight="2" >
      </Button>
      <TextView android:id="@+id/TextView01" 
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content" 
                android:text="New Place"
                android:layout_width="0dip" 
                android:layout_weight="1" >
      </TextView>
      <Button android:id="@+id/Button03" 
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:text="Save"
              android:layout_width="0dip" 
              android:layout_weight="2" >
      </Button>

Play around with the weight value and you will understand how it works :)

After this you can use the gravity property to move text to center / left or right.

Ravi Vyas
+1  A: 

i would recommend using RelativeLayout, it makes things a lot easier.

by using RelativeLayout you would be able to set the textview either center horizontal in parent or centerin parent

after doing that you would be able to either attach those buttons directly to the far sides by aligning them to the parent sides or attaching them directly to the sides of the textview, add a little padding perhaps and poof youve got your spacing.

Ben