How to Create a Custom Yes/No Dialog in Android with Kotlin?
Android AlertDialog is used to display a small window to the user to make a decision via an OK, Yes, or Cancel button or enter additional information. It is normally modal and requires the user to take any action before they can proceed. In this article, we will use AlertDialog to create a reusable generic solution when the user simply needs to reply Yes or No. A sample video is given below to get an idea about what we are going to do in this article.
Open Android Studio and import the starter project. Create a new class CustomDialog.kt to contain our dialog. Our CustomDialog is initialized with a context as it is needed by AlertDialog.Builder. The show function sets up the title and the content of the message to be displayed to the user.
Now we need to implement a mechanism to let the user react depending on which button is clicked. For that, we will use the possibility in Kotlin to declare a function as a variable. Here onResponse is a function that takes 1 argument of type ResponseType and returns nothing. The enumerate ResponseType list the possible buttons in our dialog. We could also add CANCEL.
Now the show function needs to receive the user ResponseType function as a parameter and call it when one of the 2 buttons is clicked. The final code for CustomDialog
Indeed we could also call onResponse for the CANCEL button. Now somewhere in your MainActivity for example, you could write something like:
Indeed you can customize more using an XML layout. It is also possible to provide a TextView or even a Spinner in the dialog.
Please Login to comment...