TomBomb
TomBomb

Reputation: 3296

Android laying out action bar buttons

Sorry for the somewhat boring question, but I am trying to lay out buttons on an "action bar" and am running into trouble using "layout_alignRight" and the like. What I want to achieve is the following:

|[button1] _ _ _ empty space _ _ _ [button2] [button3] [button4]|

I have a RelativeLayout enclosing where the four buttons should sit, and I've tried the following code to no avail:

<RelativeLayout android:id="@+id/actionBar"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#666666" >


    <Button android:id="@+id/button1"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignLeft="@id/actionBar"
        android:background="@drawable/buttonImg" />


    <Button android:id="@+id/button4"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_alignRight="@id/actionBar"
        android:background="@drawable/buttonImg" />


    <Button android:id="@+id/button3"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_toLeftOf="@id/button2"
        android:background="@drawable/buttonImg" />


    <Button android:id="@+id/button2"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content"
        android:layout_toLeftOf="@id/button3"
        android:background="@drawable/buttonImg" />                 


</RelativeLayout>

The buttons always seem to get stretched way out, or to all get piled up on top of each other. Does anyone know how to achieve the spacing I'm looking for?

Thanks!!!

Upvotes: 2

Views: 1025

Answers (1)

With using only relative layout, you have to anchor the left most button, then the rightmost button, and then add the two other buttons aligning left of the rightmost button:

<RelativeLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
    <Button android:id="@+id/b1" android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:text="Button1"></Button>
    <Button android:id="@+id/b4" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content"
      android:layout_alignParentRight="true"
      android:text="Button4"></Button>
    <Button android:id="@+id/b3"
      android:layout_width="wrap_content"      
      android:layout_height="wrap_content"
      android:layout_toLeftOf="@id/b4"
      android:text="Button3"></Button>
    <Button android:id="@+id/b2"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:layout_toLeftOf="@id/b3"
      android:text="Button2"></Button>
</RelativeLayout>

Upvotes: 1

Related Questions