tags:

views:

47

answers:

1

Hi, I have 4 buttons in a horizontal linear layout. I'd like the right edge of the 4th button to align with the right edge of the linear layout (equal to screen width) I've tried using android:layout_gravity="right" but it doesn't work - the right button is to the right of the 3rd one but not right aligned . Am I missing something obvious?

main.xml with only the relevant layout params only is:

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">
       <Button
           android:layout_height="fill_parent"
           android:layout_width="wrap_content">
       <Button SAME LAYOUT AS BUTTON 1>
       <Button SAME LAYOUT AS BUTTON 1>

       <Button
           android:layout_height="fill_parent"
           android:layout_width="wrap_content"
           android:layout_gravity="right" />
    </LinearLayout>
</LinearLayout>

This doesn't seem to match the stated behaviour for layout_gravity in the SDK reference :"Defines how to place the view, both its x- and y-axis, within its parent view group."

+2  A: 

I know this isn't really the proper answer to your question, but you should really consider using RelativeLayout instead of LinearLayout. It scales better to different phone screen resolutions, and you can place the buttons in the correct order by using the layout_toRightOf and layout_alignParentRight attributes in your XML (or layout_above, layout_alignParentTop, etc.). Using gravity in a linear layout won't really behave as you expect because Android is still attempting to place the widgets in a fixed position.

RelativeLayout is a bit more of a pain to get working than LinearLayout, but it's worth the trouble and is also the one which Google recommends using. Once you get the hang of it, they are very convenient to work with.

Nik Reiman
Upvoted for great justice!
benvd
Thank you Nik. I think there appears to be more scope for control with the RelativeLayout. The button's are still jumping about a bit, but I'll persevere!
NickT
@NickT, keep at it, and be sure to define the layout_align* on every control to get them properly aligned. Some more info on RelativeLayout tricks here: http://www.nikreiman.com/2010/09/android-relativelayout-ninja-fu-or-how.html
Nik Reiman
Thanks for the link. I've bookmarked it as it looks very useful. Whilst my layout looks OK as it stands, it's unmaintainable, with a Table, Linear and a Frame layout! I hate going back to the start but I've got to this time. I'll have to try really hard to follow the 'go slow' advice
NickT