Search code examples
androidandroid-layoutcenterandroid-relativelayout

How to properly center a set of buttons inside a Relative Layout?


So I have the following code which works perfectly fine but Android Studio is complaining that the use a nested Relative Layout is redundant. My question is, what's the proper way to do this?

NOTE: I want both/all the buttons centered as a whole. Not one centered button with other's relative to it

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_centerInParent="true"
       android:padding="5dp">

   <Button
       android:id="@+id/btnOpenRecyclerViewActivity"
       style="@style/MainActivityButton"
       android:text="Button 1" />

   <Button
       android:id="@+id/btnOpenNormalNotificationActivity"
       style="@style/MainActivityButton"
       android:text="Button 2"
       android:layout_below="@id/btnOpenRecyclerViewActivity" />

   </RelativeLayout>

</RelativeLayout>

enter image description here


Solution

  • Use gravity='center_vertical' on top RelativeLayout.

    <?xml version="1.0" encoding="utf-8"?>
    
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:fitsSystemWindows="true">
        <Button
            android:id="@+id/btnOpenRecyclerViewActivity"
            style="@style/MainActivityButton"
            android:text="Button 1" />
        <Button
            android:id="@+id/btnOpenNormalNotificationActivity"
            style="@style/MainActivityButton"
            android:text="Button 2"
            android:layout_below="@id/btnOpenRecyclerViewActivity"/>
    </RelativeLayout>