Search code examples
androidandroid-linearlayoutandroid-imagebutton

Placement of ImageButtons in corners of LinearLayout in Android


I am trying to place two ImageButton in the corners of a LinearLayout as shown in figure below:

enter image description here

I have tried using the android:layout_gravity attribute with the value set to left and right for the two buttons. However, they show just next to each other as shown in image below:

enter image description here

How can I place the two image buttons in the corners of the LinearLayout? I have looked up a lot of previous answers and tried them but nothing seems to work. How can this placement of image buttons be done?

The XML of the layout is in the snippet below:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|fill_horizontal"
    android:orientation="horizontal">

    <ImageButton
        android:id="@+id/prev_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left"
        android:contentDescription="@string/prev_button"
        android:src="@drawable/arrow_left"/>

    <ImageButton
        android:id="@+id/next_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:contentDescription="@string/next_button"
        android:src="@drawable/arrow_right"/>
</LinearLayout>

Solution

  • Use a RelativeLayout:

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageButton
            android:id="@+id/prev_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:contentDescription="@string/prev_button"
            android:src="@drawable/arrow_left"/>
    
        <ImageButton
            android:id="@+id/next_button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentEnd="true"
            android:contentDescription="@string/next_button"
            android:src="@drawable/arrow_right"/>
    </RelativeLayout>
    

    A relativelayout is better for positioning views at the edges of the screen