Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java
  • Android
  • Kotlin
  • Flutter
  • Dart
  • Android with Java
  • Android Studio
  • Android Projects
  • Android Interview Questions
Open In App
Next Article:
How to Change the Position of AlertDialog in Android?
Next article icon

How to Change the Position of AlertDialog in Android?

Last Updated : 10 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

AlertDialog in android is one of the UI widgets which immediately pops up to confirm the user interaction or to confirm the action which is done by the user. In most of the applications, the position of the alert dialog is in the center. In this article, it's been discussed how to change the position of the alert dialog in android. Have a look at the following image to differentiate the normal alert dialog with the center position and the alert dialog with the changed position.

Note that we are going to implement this project using both the language Java and Kotlin. 

Change the Position of AlertDialog in Android

Steps to implement the Alert Dialog with Different Position

Step 1: Create an empty activity project

  • Create an empty activity android studio project. Select Java or Kotlin as the programming language.
  • Refer to Android | How to Create/Start a New Project in Android Studio? to know how to create a project with the empty activity android studio project.

Step 2: Working with the activity_main.xml file

  • The main layout of the application contains one button which is used to build show the alert dialog at the specified position.
  • Invoke the following code inside the activity_main.xml file to implement the UI.

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout      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:layout_width="match_parent"     android:layout_height="match_parent"     android:orientation="vertical"     android:backgroundTint="@color/white"     tools:context=".MainActivity">      <Button         android:id="@+id/topAlert"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:backgroundTint="@android:color/holo_green_dark"         android:text="OPEN TOP ALERT"         android:textSize="18sp"         app:layout_constraintBottom_toTopOf="@+id/centerAlert"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="0.5"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toTopOf="parent"         app:layout_constraintVertical_chainStyle="packed" />      <Button         android:id="@+id/centerAlert"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:layout_marginTop="16dp"         android:layout_marginBottom="16dp"         android:backgroundTint="@android:color/holo_green_dark"         android:text="OPEN CENTER ALERT"         android:textSize="18sp"         app:layout_constraintBottom_toTopOf="@+id/bottomAlert"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="0.5"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/topAlert" />      <Button         android:id="@+id/bottomAlert"         android:layout_width="wrap_content"         android:layout_height="wrap_content"         android:backgroundTint="@android:color/holo_green_dark"         android:text="OPEN BOTTOM ALERT"         android:textSize="18sp"         app:layout_constraintBottom_toBottomOf="parent"         app:layout_constraintEnd_toEndOf="parent"         app:layout_constraintHorizontal_bias="0.5"         app:layout_constraintStart_toStartOf="parent"         app:layout_constraintTop_toBottomOf="@+id/centerAlert" />   </androidx.constraintlayout.widget.ConstraintLayout> 

Output UI:

alert-box-position-ui


Step 3: Working with the MainActivity.java file

For changing the alert dialog position at the top of the Android window, invoke the following code to implement. Comments are added for better understanding.

MainActivity File:

Java
package org.geeksforgeeks.demo;  import android.os.Bundle; import android.view.Gravity; import android.view.Window; import android.widget.Button; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity;  public class MainActivity extends AppCompatActivity {      // Creating Button instance     private Button topAlert, centerAlert, bottomAlert;      // Overriding the onCreate Method     @Override     protected void onCreate(Bundle savedInstanceState) {         super.onCreate(savedInstanceState);         setContentView(R.layout.activity_main);          // Register buttons with their respective IDs         topAlert = findViewById(R.id.topAlert);         centerAlert = findViewById(R.id.centerAlert);         bottomAlert = findViewById(R.id.bottomAlert);          // Handle the "Top Alert" button click         topAlert.setOnClickListener(v -> {             AlertDialog alertDialog = createAlertDialog("Top Alert dialog");             showAlertWithGravity(alertDialog, Gravity.TOP);         });          // Handle the "Center Alert" button click         centerAlert.setOnClickListener(v -> {             AlertDialog alertDialog = createAlertDialog("Center Alert dialog");             showAlertWithGravity(alertDialog, Gravity.CENTER);         });          // Handle the "Bottom Alert" button click         bottomAlert.setOnClickListener(v -> {             AlertDialog alertDialog = createAlertDialog("Bottom Alert dialog");             showAlertWithGravity(alertDialog, Gravity.BOTTOM);         });     }      /**      * Helper method to create an AlertDialog with a specified message.      */     private AlertDialog createAlertDialog(String message) {         AlertDialog.Builder builder = new AlertDialog.Builder(this)                 .setIcon(R.drawable.gfg_logo)                 .setTitle("This is Alert Dialog")                 .setMessage(message)                 .setNeutralButton("DISMISS", (dialog, which) -> dialog.dismiss());          return builder.create();     }      /**      * Helper method to show an AlertDialog and set its gravity.      */     private void showAlertWithGravity(AlertDialog alertDialog, int gravity) {         alertDialog.show();         Window window = alertDialog.getWindow();         if (window != null) {             window.setGravity(gravity);         }     } } 
Kotlin
package org.geeksforgeeks.demo  import android.os.Bundle import android.view.Gravity import android.widget.Button import android.widget.Toast import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity   class MainActivity : AppCompatActivity()  {     override fun onCreate(savedInstanceState: Bundle?) {         super.onCreate(savedInstanceState)         setContentView(R.layout.activity_main)          // register the button with it's appropriate ID         val topAlert: Button = findViewById(R.id.topAlert)         val centerAlert: Button = findViewById(R.id.centerAlert)         val bottomAlert: Button = findViewById(R.id.bottomAlert)           // handle the SHOW ALERT DIALOG BUTTON         topAlert.setOnClickListener {             val builder = AlertDialog.Builder(this)                 .setIcon(R.drawable.gfg_logo)                 .setTitle("This is Alert Dialog")                 .setMessage("Top Alert dialog")              // setup neutral button             builder.setNeutralButton("DISMISS") { _, _ -> }              // show the alert dialog             val alertDialog = builder.create()             alertDialog.show()              // set the gravity of the window to the top             alertDialog.window!!.setGravity(Gravity.TOP)         }          centerAlert.setOnClickListener {             val builder = AlertDialog.Builder(this)                 .setIcon(R.drawable.gfg_logo)                 .setTitle("This is Alert Dialog")                 .setMessage("Center Alert dialog")              // setup neutral button             builder.setNeutralButton("DISMISS") { _, _ -> }              // show the alert dialog             val alertDialog = builder.create()             alertDialog.show()              // set the gravity of the window to the top             alertDialog.window!!.setGravity(Gravity.CENTER)         }          bottomAlert.setOnClickListener {             val builder = AlertDialog.Builder(this)                 .setIcon(R.drawable.gfg_logo)                 .setTitle("This is Alert Dialog")                 .setMessage("Bottom Alert dialog")              // setup neutral button             builder.setNeutralButton("DISMISS") { _, _ -> }              // show the alert dialog             val alertDialog = builder.create()             alertDialog.show()              // set the gravity of the window to the top             alertDialog.window!!.setGravity(Gravity.BOTTOM)         }     } } 

Output:


Next Article
How to Change the Position of AlertDialog in Android?

A

adityamshidlyali
Improve
Article Tags :
  • Java
  • Technical Scripter
  • Android
  • Technical Scripter 2020
  • Kotlin Android
  • Java-Android
Practice Tags :
  • Java

Similar Reads

    How to Change Alert Dialog Position on Screen in Android?
    AlertDialog in Android is an alert message that appears in the form of a pop-up consisting of four elements namely a title, a message, a positive button, and a negative button. The positive and the negative buttons are clickable and can be programmed for performing an action. However, the AlertDialo
    2 min read
    How to Create a Full Screen AlertDialog in Android?
    AlertDialog in Android is an alert message programmatically displayed to the user over the change of course of action. This appears as a pop-up and has four elements i.e., a title, a message, a positive button, and a negative button. Typically, AlertDialog is non-customized and appears as an overlay
    2 min read
    How to Prevent AlertDialog Box From Closing in Android?
    In Android, AlertDialog is a simple alert message that appears in the form of a pop-up that consists of a title, a message, and two buttons namely positive and negative buttons. The user basically has to click on one of the two buttons to reply to the message in the AlertDialog. The negative button
    3 min read
    How to Implement Loading AlertDialog in Android?
    AlertDialog is defined as the small window that shows a particular message to the user when the user performs or commits certain action. In this article, we are going to build a simple android application in which we learn how to implement a Loading AlertDialog that means whenever the user clicks on
    6 min read
    How to Create a Custom AlertDialog in Android?
    In some cases for the AlertDialog, there is a need to get input from the user or customize it according to our requirements. That's where custom AlertDialogs comes in handy. In this article we are going to discuss on how to customize the AlertDialogs and take user input.Example: Steps to Implement o
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences