Thursday, December 26, 2024
Google search engine
HomeLanguagesJavaHow to Center a Button in a Linear Layout in Android?

How to Center a Button in a Linear Layout in Android?

LinearLayout is a view group that aligns all children vertically or horizontally in a single direction. The “android:orientation” parameter allows you to define the layout direction. A button is a component of the user interface that can be tapped or clicked to carry out an action. Nowadays while developing one of our applications, we wanted to have center-aligned buttons, while in one application we were using LinearLayout and It’s Looking Pretty Nice For Our Application.

We will be building a simple application in which we will be displaying a button in the center of the screen with LinearLayout.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Project just refer to this article on How to Create New Project in Android Studio. The code can be implemented in both Java and Kotlin Programming Language for Android.

Step 2: Working with the activity_main.xml File

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

XML




<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:gravity="center" >
      
    <!-- Button centering in screen -->
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="GeeksForGeeks" />
</LinearLayout>


Since there is no change in the Java/Kotlin MainActivity File, we’ve only provided the XML File Code.

Output:

Center Button in Linear Layout

 

RELATED ARTICLES

Most Popular

Recent Comments