Mon. May 6th, 2024

Alert Dialog is a window that pops up on the screen. They generally show some information and ask for a user action. There are three core components that build an Alert Dialog.

  • Title Text
  • Message Text
  • Buttons – There are three types of buttons: Positive, Negative, and Neutral

dialog style.

Alert Dialog Methods

Some of the methods that can be used on an AlertDialog.

  • setTitle
  • setMessage
  • setIcon
  • setCustomTitle – Here you can pass a custom view that’ll be put in place of the title part in the alert dialog.
  • setPositiveButton – We pass the string name, as well as Button, clicked callback method here.
  • setView – used to add a custom view inside the alert dialog.
  • setList – used to set an array of strings which would be displayed in the form of a List.
  • setMultiChoiceList – again we can set an array but this time we can select multiple items from the List thanks to CheckBox.
  • setPositiveButtonIcon – set an icon alongside the Button
  • show() – used to display the AlertDialog
  • setDismissListener – Inside this, you can set the logic to be triggered when the alert dialog is dismissed.
  • setShowListener – set the logic to be triggered when the alert dialog is dismissed.
  • setCancelable – requires a boolean value. By default all alert dialogs are cancelable on button click or touch outside. If this method is set to false, you need to explicitly cancel the dialog using dialog.cancel() method.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Dialogs example"
         />

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/predefined"
        android:text="Predefined"></Button>   

</LinearLayout>
</layout>

MainActivity.kt

package com.androindian.alerts

import android.annotation.SuppressLint
import android.app.DatePickerDialog
import android.app.Dialog
import android.app.ProgressDialog
import android.app.TimePickerDialog
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Button
import android.widget.DatePicker
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import com.androindian.alerts.databinding.ActivityMainBinding
import java.text.SimpleDateFormat
import java.util.*

class MainActivity : AppCompatActivity() {

    var binding: ActivityMainBinding?=null
    

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding=DataBindingUtil.setContentView(this,R.layout.activity_main)


        binding?.predefined?.setOnClickListener {
            var predefined=AlertDialog.Builder(this)
            predefined?.setTitle("Are you Sure")
            predefined?.setMessage("Want to close")
            predefined?.setPositiveButton("Yes" ){dialogInterface, which ->
                Toast.makeText(applicationContext,"clicked yes",Toast.LENGTH_LONG).show()
            }
            predefined?.setNegativeButton("No" ){dialogInterface, which ->
                Toast.makeText(applicationContext,"clicked No",Toast.LENGTH_LONG).show()
            }

            predefined?.setNeutralButton("Cancel" ){dialogInterface, which ->
                Toast.makeText(applicationContext,"clicked Cancel", Toast.LENGTH_LONG).show()
            }

            predefined.show()
        }

       

        }
}

build.gradle

plugins {
    id 'com.android.application'
    id 'org.jetbrains.kotlin.android'
}

android {
    namespace 'com.androindian.alerts'
    compileSdk 33

    defaultConfig {
        applicationId "com.androindian.alerts"
        minSdk 24
        targetSdk 33
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }
    kotlinOptions {
        jvmTarget = '1.8'
    }
    dataBinding{
        enabled=true
    }
}

dependencies {

    implementation 'androidx.core:core-ktx:1.7.0'
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.5'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.5.1'
}

By Rajashekar

I’m (Rajashekar) a core Android developer with complimenting skills as a web developer from India. I cherish taking up complex problems and turning them into beautiful interfaces. My love for decrypting the logic and structure of coding keeps me pushing towards writing elegant and proficient code, whether it is Android, PHP, Flutter or any other platforms. You would find me involved in cuisines, reading, travelling during my leisure hours.

Leave a Reply

Your email address will not be published. Required fields are marked *