Kotlin Alertdialog Code
Below is sample code for displaying an Alertdialog using Kotlin. It has 3 button click listeners.
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setTitle("Kotlin Alert Dialog")
showDialog("Kotlin Sample Code", "Alertdialog")
}
private fun showDialog(title: String, message: String){
// Late initialize an alert dialog object
lateinit var dialog: AlertDialog
// Initialize a new instance of alert dialog builder object
val builder = AlertDialog.Builder(this)
// Set a title for alert dialog
builder.setTitle(title)
// Set a message for alert dialog
builder.setMessage(message)
// On click listener for dialog buttons
val dialogClickListener = DialogInterface.OnClickListener{ _, which ->
when(which){
DialogInterface.BUTTON_POSITIVE -> {
Toast.makeText(this@MainActivity, "POSITIVE button clicked", Toast.LENGTH_LONG).show()
}
DialogInterface.BUTTON_NEGATIVE -> {
Toast.makeText(this@MainActivity, "NEGATIVE button clicked", Toast.LENGTH_LONG).show()
}
DialogInterface.BUTTON_NEUTRAL -> {
dialog.dismiss()
}
}
}
// Set the alert dialog positive/yes button
builder.setPositiveButton("POSITIVE",dialogClickListener)
// Set the alert dialog negative/no button
builder.setNegativeButton("NEGATIVE",dialogClickListener)
// Set the alert dialog neutral/cancel button
builder.setNeutralButton("CANCEL",dialogClickListener)
// Initialize the AlertDialog using builder object
dialog = builder.create()
// Finally, display the alert dialog
dialog.show()
}
}
Android Kotlin Alertdialog Screenshot
Comments
Post a Comment