Search code examples
androidbuttonscaleandroid-relativelayout

Auto scaling button's width in RelativeLayout


<?xml version="1.0" encoding="utf-8"?>

  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical" android:layout_width="match_parent"
        android:layout_height="match_parent">

    <Button
        android:id="@+id/btn1"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" />

    <Button

        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_toRightOf="@+id/btn1"/>

     <Button
        android:id="@+id/btn2"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_toRightOf="@+id/btn1"/>

      <!--x7-->

I put 7 buttons in its relativelayout. And I'd like to adjust their 'width' to the same size to fit the screen. What should I do


Solution

  • You can use LinearLayout as a parent and can give weight and weightsum to achieve that, Using Relative layout you can't fit the entire screen or it may exceed the screen based on the device.

    You can achieve this using LinearLayout like below,

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