Search code examples
android-relativelayoutandroid-imagebutton

How to make 2 horizontal buttons to fill relative layout equally?


ddd

the corresponding xml layout:

  <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/buttons_holder"
    android:layout_below="@+id/list_holder"
    android:layout_alignParentBottom="true">

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/previous_button"
        android:src="@android:drawable/ic_media_previous"
        android:layout_alignParentLeft="true"
        android:minWidth="150dp"
        android:layout_alignParentBottom="false"
        android:layout_alignParentRight="false"
        android:layout_alignParentTop="false"
        android:scaleType="fitEnd" />

    <ImageButton
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/forward_button"
        android:src="@android:drawable/ic_media_next"
        android:layout_alignParentRight="true"
        android:minWidth="150dp"
        android:scaleType="fitStart"
        android:layout_alignWithParentIfMissing="false" />
</RelativeLayout>

I can change button's width just by setting

minWidth = 200dp maxWidth = 200dp

so the button will occupy fixed space inside my relative layout

but i want to do it the 'right way' - using probably gravity, but there is no gravity for button - only for my relative layout that holds these 2 buttons

How to properly make 2 buttons occupy equal space inside rel layout?


Solution

  • you can use @Onik's suggestion. If you want to use RelativeLayout only then

    1. Place dummy view in center of RelativeLayout
    2. Put button1 toLeft of dummy view
    3. Put button2 toRight of dummy view

    Sample Code:

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
    
       <ImageButton
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_toLeftOf="@+id/dummy" />
    
       <View
           android:id="@+id/dummy"
           android:layout_width="1dp"
           android:layout_height="1dp"
           android:layout_centerHorizontal="true" />
    
      <ImageButton
           android:layout_width="match_parent"
           android:layout_height="wrap_content"
           android:layout_toRightOf="@+id/dummy" />
    
    </RelativeLayout>