Search code examples
androidandroid-layoutactionbarsherlock

ActionBarSherlock with custom titlebar - weight distribution no working


I'm trying to implement a custom title bar with ActionBarSherlock. The title bar should have two buttons in its left and right edges, and a textview in the center. The textview should occupy the space between the two buttons.

I've tried setting the layout_weight, but for some reason it had no effect at all.

This is the custom layout I have in res/layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >

<Button
    android:id="@+id/btn_left"
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:text="Left" />

<TextView
    android:id="@+id/header"
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:gravity="center_horizontal"
    android:layout_weight="4"
    android:text="Header Text" />

<Button
    android:id="@+id/btn_right"
    android:layout_width="0dip"
    android:layout_height="match_parent"
    android:layout_weight="1"
    android:text="Right" />

</LinearLayout>

Right now all the elements just float to the left and I have no idea why, what am I doing wrong?


Solution

  • Instead of using a LinerLayout try using a RelativeLayout.

    Edit: made center text view strech to buttons (make sure to leave TextView match_parent..

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
    
        <Button android:id="@+id/leftButton" 
                android:layout_alignParentLeft="true"....
    
        <TextView android:layout_centerHorizontal="true"
                  android:layout_toLeftOf="@id/rightButton"
                  android:layout_toRightOf="@id/leftButton"  ....
    
        <Button android:id="@+id/rightButton"
                android:layout_alignParentRight="true"....
    
    
    </RelativeLayout>