The Quick and Easy Way to Create an Android Dialog
When coding and having own workflow, sometimes there is a need to display some information in a simple but clear and good way. Personally I think that dialog boxes are a clever way to to this – work every time and there is no any additional need to modify it. I decided to write this post be a quick tip for later development processes.
Below you can find a simple part of code for create and later display a dialog. If you have any question, leave a comment below. Enjoy!
The solution
// Prerequisite import and a package setup. package com.sunnylib.secondapplication import android.content.DialogInterface import android.os.Bundle import androidx.appcompat.app.AlertDialog import androidx.appcompat.app.AppCompatActivity // The main Activity class class MainActivity : AppCompatActivity() { // A function for building a dialog. // Accepts two strings: title and context message. // Returns a complex dialog object. private fun buildDialog(title: String, message: String): AlertDialog { val alertDialogBuilder = AlertDialog.Builder(this) alertDialogBuilder.setTitle(title) alertDialogBuilder.setMessage(message) alertDialogBuilder.setPositiveButton(R.string.ok, DialogInterface.OnClickListener { dialog, which -> dialog.cancel() }) return alertDialogBuilder.create() } // Private function for displaying a previously built dialog. private fun displayValidationDialog() { val alertDialog = buildDialog(title = "R.string.warning", message = "R.string.all_fields_required") alertDialog.show() } // Basic activity class, runs as a first method on the activity launch. // For this example, the dialog displays immediately. override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) displayValidationDialog() } }