Search code examples
javaandroidandroid-relativelayoutandroid-toolbar

Move toolbar to top of relative layout


I am trying to put my button in the center, but keep my toolbar at the top. At the moment both are in the middle because of the gravity "center".

Is there a way to do this without using padding attributes? Otherwise it will look different on other screen sizes.

Here is my main_activity:

<RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_gravity="center">

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:minHeight="?attr/actionBarSize"
    android:background="#2196F3"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:android="http://schemas.android.com/apk/res/android">

</android.support.v7.widget.Toolbar>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true" />


</RelativeLayout>

Solution

  • It is simple, change to this:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="match_parent" >
    
        <android.support.v7.widget.Toolbar
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:background="#2196F3"
            android:minHeight="?attr/actionBarSize" >
        </android.support.v7.widget.Toolbar>
    
        <Button
            android:id="@+id/button"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerInParent="true"
            android:text="New Button" />
    
    </RelativeLayout>