Lv99Zubat
Lv99Zubat

Reputation: 853

How do I force a button to the right in a horizontal linear layout with another button to the left of it?

I have 2 buttons (left and right) side by side in a linear layout (horizontal). I want left to take all of the space if right is blank. If right has content, I want it to stick to the right and then left fills as much of the remaining space that it can. How do I do this?

Pretty sure I have to use linear layout because a relative layout will cause overlap.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"        
    android:gravity="center_vertical"
    android:orientation="horizontal" >

    <Button            
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:ellipsize="end"
        android:singleLine="true"   
        android:text="this text takes priority and kicks everything off screen (not desired behavior)" />

    <View
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_weight="1"/>  

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"             
        android:text="i need this text to take priority over the other button"/>
</LinearLayout>

Upvotes: 0

Views: 681

Answers (2)

Evan Bashir
Evan Bashir

Reputation: 5551

A RelativeLayout will work well for this. By anchoring both buttons to their respective sides with alignParent, and positioning the first button to the left of the second with toLeftOf – you'll achieve a flexible left button, that will not overlap the right button.

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_toLeftOf="@id/button2"
        android:text="Left Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:text="Right Button"/>
</RelativeLayout>

Upvotes: 1

UMESH0492
UMESH0492

Reputation: 1731

This can be easily achievable by relative layout and is always recommended to use relative layout. Just make view for left first and make is wrap content and make another view with match parent respectively.

Upvotes: 0

Related Questions