How to show a Dialog in Android Kotlin ?

Sudish Kumar
2 min readDec 1, 2020

--

What is a Dialog ?

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

Now we will create an success alert dialog .

Workflow

  1. We we create a fun succeseAlertDialog() in a .kt class file because if we have need same dialog more than one place in a screen.
  2. After we will set click event on a button and call the succeseAlertDialog() in it’s body.
  3. Just run the code.

Let’s coding .

MainActivity.kt

class MainActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState) setContentView(R.layout.activity_main)btn_booking.setOnClickListener {showBookingAlertSuccessfully()

}
}
private fun showBookingAlertSuccessfully(){
val bookingAlert = AlertDialog.Builder(this)
bookingAlert.setTitle("Booking Successfully.")

bookingAlert.setMessage("Your Booking is completed. \nYour Servicing Date is 2020–12–29\n and Time is 15:58 .\n\nFor any help please visit on help page.")
bookingAlert.setIcon(R.drawable.type_success)bookingAlert.setPositiveButton("Ok"){dialog, id ->
val intent = Intent(this,MyServicesActivity::class.java)
startActivity(intent)
finish()
}

val alertDialog = bookingAlert.create()
alertDialog.setCanceledOnTouchOutside(false)
alertDialog.show()
}
}

Note; if you have to use the dialog in fragment then you have to use activity (this) .

Customise Alert Dialog

For creating costume dialog you can add a new .xml file, like bellow I am adding a send_feedback_layout.xml file to dialog.

val inflater = layoutInflater

val inflateView = inflater.inflate(R.layout.send_feedback_layout, null)

val feedbackRating = inflateView.findViewById<RatingBar>(R.id.feedback_ratingBar)

feedbackRating.rating = 5.0

// simply add this layout to alert dialog like this

alertDialog.setView(inflateView)

How to add alignment in alert dialog?

alert.window!!.setGravity(Gravity.BOTTOM)

It’s working proper.

Thank you friends for reading my article I hope it’s helpful for you.

--

--

Sudish Kumar
Sudish Kumar

Written by Sudish Kumar

Flutter | Android | Node | Dart | Kotlin | Java | JavaScript | TypeScript | PHP | Short Story Teller | Tech Lead

No responses yet