How to center views in LinearLayout and RelativeLayout ?

Recently while developing one of our application, we wanted to have center aligned buttons, while in one application we were using LinearLayout, in another application we were using RelativeLayout.

So in this post, we will show you how you can center any view in Linear and Relative layouts.

Centre views / buttons in LinearLayout

For adjusting any view to center in LinearLayout, you will need to modify your layout file with parameter android:layout_gravity=”center”

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/linear_layout_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    <Button
        android:id="@+id/btn_start_stop"
        android:text="Linear Layout Center Button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center" />

 </LinearLayout>

Center views / buttons in RelativeLayout

For adjusting any view to center, you will need to modify your layout file with parameter android:layout_centerInParent=”true”

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"

    android:id="@+id/relative_layout_root"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent">

    <Button
        android:id="@+id/btn_start_stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Relative Layout Center Button"
        android:layout_centerInParent="true"/>
</RelativeLayout>
Google Sheets Import Data - Import ... x
Google Sheets Import Data - Import from multiple spreadsheets to one range

Leave a Comment

Sign up to our newsletter!

ADB Commands Android Android Applications Android Build system Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia NDK / Middleware / HAL Operating System Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto Embedded Linux