Open In App

How to Change Alert Dialog Position on Screen in Android?

Last Updated : 13 Jan, 2022
Like Article

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 AlertDialog appears in the center of the screen whenever called. Below is a screenshot of an AlertDialog.

Through this article, we will show you how you could change the position of the AlertDialog on the screen. Follow the below steps once the IDE is ready.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.

Step 2: Working with the activity_main.xml file

In our demonstration, upon button click, the AlertDialog shall be displayed. So we added a Button in our layout file.


<?xml version="1.0" encoding="utf-8"?>
    <!-- AlertDialog is displayed when 
         this button is clicked -->
        android:text="show dialog"/>

Step 3: Working with the MainActivity.kt file

Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.


package org.geeksforgeeks.dialogpositionchange
import android.os.Bundle
import android.view.Gravity
import android.widget.Button
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        // Declaring and initializing a constant for 
        // Button from the layout file (activity_main.xml)
        val mButton1 = findViewById<Button>(
        // Declaring and initializing a 
        // constant for AlertDialog Builder
        val mBuilder = AlertDialog.Builder(this)
        // Attributing the AlertDialog Builder
        // On Button click, AlertDialog is created and displayed.
        // Gravity of the AlertDialog is set to TOP to display
        // AlertDialog in the TOP of the screen.
        mButton1.setOnClickListener {
            val mAlert = mBuilder.create()
            // Similarly we can change the gravity 
            // to left right and bottom.


You can see that when the button is clicked, the AlertDialog appears at the top of the screen.

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads