Alert Dialog in Kotlin
activity_alert_dialog_example.xml
This activity activity_alert_dialog_example.xml we are creating a button which on click will display the alert dialog
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlertDialogExample"
android:orientation="vertical"> <Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/alertButton"
android:text="Alert Dialog Example"/> </LinearLayout>
AlertDialogExample.kt
AlertDialogExample.kt file we are intiallizing the button which on click displays alert dialog which contains title, message ,icon and buttons which perform there respective actions
package com.example.kotlinsampleproject import android.support.v7.app.AppCompatActivity import android.os.Bundle import android.support.v7.app.AlertDialog import android.widget.Button import android.widget.Toast class AlertDialogExample : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_alert_dialog_example) val button = findViewById<Button>(R.id.alertButton) //on button click alert dialog will be displayed button.setOnClickListener { val builder = AlertDialog.Builder(this) // set title for alert dialog
builder.setTitle("Welcome to SDK Book") //set message for alert dialog
builder.setMessage("Are you happy with the content...?") //set icon for alert dialog
builder.setIcon(R.drawable.logo) //postive action button in alert dialog
builder.setPositiveButton("Yes"){dialogInterface, i ->
Toast.makeText(this,"You have clicked on Yes...!Thanks",Toast.LENGTH_LONG).show() }
//negative action button in alert dialog builder.setNegativeButton("No"){dialogInterface, i ->
Toast.makeText(this,"You have clicked on No...!Sad",Toast.LENGTH_LONG).show() } //netural action button in alert dialog
builder.setNeutralButton("Cancel"){dialogInterface, i ->
Toast.makeText(this,"You have clicked on Cancel...!Thanks",Toast.LENGTH_LONG).show() } //Create the Alert Dialog
val alerDialog :AlertDialog = builder.create() //dismiss alert dialog when clicked on screen
alerDialog.setCancelable(false) alerDialog.show(); } } }
Happy Reading 😊 Thank You Sushmitha N Hi there ! Im a experienced android developer with 4years of revelant exprience.My Skills include Android,Core Java ,Oops and Kotlin.Youtube Channel : SDK Book
Comments
Post a Comment