Bazinga
Bazinga

Reputation: 499

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

Upvotes: 1

Views: 80

Answers (2)

jauser
jauser

Reputation: 284

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>

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191681

You might be able to do an outer FrameLayout with centered gravity.

Or, the inner RelativeLayout could be a LinearLayout.

Or, perhaps just one RelativeLayout around your buttons that is centered in the parent, but wraps the content rather than matching the parent layout height.

Upvotes: 0

Related Questions