Search code examples
androidandroid-layoutandroid-relativelayout

Spacing between two buttons in RelativeLayout in Android xml


I have a relative layout that has two buttons. I'm trying to set the relative positions of these two dynamically so that on different screen sizes, it looks same. The position of the layout is getting set correctly basing on screen size but the spacing between the buttons is not getting.

<RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/buttonLine"
        android:layout_above="@+id/separator">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"
        android:background="@drawable/skip"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_marginLeft="60dp"/>



    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/buttonClr"
        android:background="@drawable/clear"
        android:layout_alignParentTop="true"
        android:layout_alignParentRight="true"
        android:layout_marginRight="60dp"/>

    </RelativeLayout>

In my java class I have a method for the dynamic part. I'm using this piece of code there for this button-relative-layout.

button_line.getLayoutParams().height = getHorizontalRatio(40); //button_line is RelativeLayout
 skip.setPadding(getHorizontalRatio(40), 0, 0, 0); //skip and clear are the buttons
 clear.setPadding(getHorizontalRatio(400), 0, 0, 0);
skip.getLayoutParams().width = getHorizontalRatio(75);
            skip.getLayoutParams().height = getHorizontalRatio(25);
            clear.getLayoutParams().width = getHorizontalRatio(75);
            clear.getLayoutParams().height = getHorizontalRatio(25);

PS: I have tried changing the ratios and changing the layout to LinearLayout(which I didn't understand completely). Please suggest something.


Solution

  • Is this what you want?

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                  android:layout_width="match_parent"
                  android:layout_height="match_parent"
                  android:orientation="horizontal"
                  android:padding="20dp"
                  android:weightSum="2">
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginRight="10dp"
            android:layout_weight="1"
            android:text="Button 1"/>
    
        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="10dp"
            android:layout_weight="1"
            android:text="Button 2"/>
    
    </LinearLayout>
    

    enter image description here