Custom dialog android kotlin

How to create a Custom Progress Dialog in Android using Kotlin

In this tutorial, I’m going to show you how to make a Custom Progress Dialog for your Android app.

A Progress Dialog is a dialog with a progress indicator and text message.

Progress Dialog is useful while you’re doing some task on your app that needs time to complete, like getting data from a server, because you don’t want to leave your users staring at their screens without letting them know that something is happening in the background.

Let’s get started!

In this example, we’re going to use CardView to give our Progress Dialog nice rounded corners. If you don’t want this, skip this step and use RelativeLayout instead.

Add the CardView dependency in the app-level of build.gradle:

Making the Custom Progress Dialog Layout

Go to res > layout and create the Custom Progress Dialog layout (progress_dialog_view.xml):

Creating the Custom Progress Dialog

Now, create the Kotlin class, named CustomProgressDialog.kt, and paste inside:

Now, go to res > values > styles.xml to set the theme for the Dialog:

Using the Custom Progress Dialog

To use it, just declare the class CustomProgressDialog at the beginning of your Activity:

… and show the Dialog with a title or not…

… and dismiss it using:

If you have any questions, please feel free to leave a comment below

Источник

Android Custom AlertDialog Tutorial Using Kotlin

by Dody Prasetya · January 18, 2020

Whenever you need to show a custom message or alert on your app, then you need an Android custom AlertDialog. It is very easy to learn and implement! You want to show an alert containing a message? Or, you want to show a custom style alert? Then this tutorial is right for you.

Basically the alert message on Android is using an existing class from the Android framework and that is the AlertDialog. It has many styles like displaying a simple alert message, a multiple choices alert, a list of items alert, a custom layout alert dialog, etc.

What the app will look like?

The app will look like this after you finish this tutorial:

What will you learn?

  • Understand how to implement and show an AlertDialog on the Android app.
  • Learn about different types of AlertDialog (simple, multiple choices, list of items, custom layout, etc) and use some of them.
  • Implement the listener from AlertDialog buttons.

Note: In this post, I used Android Studio 3.5.3, make sure you use the latest Android Studio, or if you already install it, be sure to check the latest update. The Kotlin version that I used is Kotlin 1.3.61.

Getting Started – Android Custom AlertDialog

Open your Android Studio and choose to Start a new Android Studio Project. Then set the Application Name CustomAlertDialog and select Kotlin as the language. Give the Activity Name MainActivity and wait until the Android Studio finishes preparing your project.

Читайте также:  Андроид пропала клавиатура остался голосовой ввод

Open activity_main.xml inside res/layout directory and replace the code given below:

That’s it for the first step of creating a screen that contains some buttons to show each alert dialog later.

Next, open MainActivity.kt file and add each of these functions:

Simple AlertDialog

Add a new function showSimpleAlert() here:

There are some methods or function from AlertDialog that we use here:

  • setTitle() is for giving the dialog a title.
  • setMessage() is setting a message for the dialog.
  • setPositiveButton() . This method is for giving the dialog a positive button and its listener/action when the button is pressed.
  • setNegativeButton()
  • setNeutralButton()
  • show() , this function is to show the AlertDialog.

List of Items AlertDialog

Add a new function showListAlert() here:

The setItems() function takes a parameter that is an Array of Strings as a list of items for it.

Multiple Choices AlertDialog

Add a new function showMultipleChoicesAlert() here:

The setMultiChoiceItems() is also takes a parameter of Array of Strings. There is also a conditional ( isChecked ) to point out which items that have already been selected.

Custom AlertDialog

Add a new function showCustomAlert() here:

Create a new layout resource file named dialog_custom_layout.xml and put this code inside it:

The setView() is a method to set the custom view or layout of the dialog. In this case, we inflate the dialog_custom_layout.xml to the view and put is as a parameter to setView() .

EditText AlertDialog

Add a new function showSimpleAlert() here:

It is similar to the custom dialog style before, but the difference is the view is created programmatically. This example is an EditText.

So, that is all for AlertDialog types for this tutorial. The next step is setting the listeners for each button that you created earlier. Open MainActivity.kt again, and modify the onCreate() method.

And now it is time to run the app and see the dialogs yourself!

Where to go next?

You can download this full code from the link below:

Be sure to check my other cool posts here about:

Hope you like my post, comment and share it with love!

Источник

Getting Started with Dialogs in Android Kotlin

February 14, 2021

Android has distinguished techniques for improving user experience. One of them is the use of dialogs. A Dialog is a brief conversation between the user and the application. It is usually a small window that pops-up on the device’s screen.

Dialogs can be used to prompt actions in some events or pass a message to the user. In this tutorial, we are going to learn how to create and implement dialogs in Android.

Prerequisites

Before we move on, make sure that you:

  • Have Android Studio installed on your machine.
  • Know how to create Android projects and navigate through the IDE .
  • Are familiar with XML and the Kotlin programming language.
  • Have basic knowledge of Data binding .

Getting started

Android offers several types of Dialogs which include:

  • Alert Dialog
  • DatePicker Dialog
  • TimePicker Dialog
  • Dialog Fragment
  • BottomSheet Dialog

In this tutorial, we’re going to lay our focus on AlertDialog , and we’ll mainly cover the following concepts:

Creating Alert dialogs:

  • Adding title, buttons, message, and an icon.
  • Handle dialog events.

Customizing Alert dialogs:

  • Creating custom layout resource file.
  • Use of DataBinding to access views.
  • Creating a round-corner-shape dialog.

Creating an Android project

Launch Android Studio and create an Empty Activity project with the following specifications.

Читайте также:  Планшет android емкостной экран

Name : Dialogs in Android

Project setup

Adding Dependencies and Plugins

For us to use DataBinding, we have to enable and add the necessary plugin first. Open the app-level build.gradle file and add the following in the respective scope.

Sync and wait for the Gradle-build to finish. Once it’s done, proceed to set up the UI.

Setting up the user interface

In our UI, we need 2 buttons that we’ll use to show the Dialogs. Open activity_main.xml file and paste the code below.

To fix the error about the unresolved reference in the text attribute, create strings in the strings resources as shown below.

As we mentioned earlier, we will use these buttons to show the necessary dialogs. To achieve this, we need DataBinding objects for each view in our layout.

The beauty of DataBinding is that it autogenerates these objects. We just need to enclose the layout with a layout tag as shown below.

Writing Kotlin code

Inside the MainActivity.kt file is where we’ll write the logic of our app. First, create a mutable variable of type ActivityMainBinding that will initially be null but be initialized in the onCreate() method.

To learn more about DataBinding please refer to this article by Michael Barasa or this Youtube tutorial.

When activities or fragments are destroyed, variables or objects can still be holding a reference to non-existing values. This is called a memory leak which of course can lead to unwanted behavior in our app.

To avoid this, always de-allocate memory allocated to such objects in the onDestroy() method.

The snippet below shows the above-discussed concepts.

Creating Alert Dialogs

An Alert Dialog is created by instantiating the AlertDialog class and then creating a Builder for it. There are several types of Alert Dialogs in Android. In this tutorial, we’ll create every dialog in its own function and the respective one will be called when a button is clicked.

A). Default Alert Dialog

This type of dialog is usually rectangular and appears at the center of the screen. We’ll discuss its functionalities as we proceed. In the meanwhile, paste the code below inside the MainActivity class, just below the onCreate() method.

The code above creates a dialog with the title “Hello” and shows it on the screen using the show() method. If omitted, the dialog won’t pop up. You can verify this by calling its function when the button is clicked. Add the code below.

Ensure that there are no errors in your code before running the app. When you click the button, you should get an output similar to the one below.

Adding features to a Dialog

Now that we’ve created a Dialog, we can add functionalities such as:

  • Icon — This is a small-sized image that appears alongside the title. It usually makes the dialog more informative and attractive.
  • Message — This is the main content of the alert dialog. It gives a short description of the reason for its pop-up or, prompts the user to make a decision before proceeding.
  • Buttons — They appear at the bottom part of the dialog. There are three types of buttons namely, Positive , Negative and Neutral buttons. As their names suggest, they are meant to perform the respective actions once clicked. By default, the dialog dismisses once any of the buttons is clicked.
  • View — this is a layout used in customizing dialogs. We’ll learn about this in a moment.

Meanwhile, let us create a Dialog that implements the above features. Create a vector drawable (icon) named ic_hello .

Читайте также:  Что такое бэкап файлов андроид

Update the showDefaultDialog() function to look like the one below.

Now, copy and paste the code below just above or below the showDefaultDialog() function.

Explanation

The syntax for creating a button requires us to pass in a listener of type DialogInterface.OnClickListener in the lambda function. A DialogInterface defines a dialog-type class that can be shown, canceled (or dismissed), and may have buttons that can be clicked. Kotlin simplifies this by allowing us to pass in underscores for unused arguments in the lambda function.

The function toast() is used to show a short Toast message with a text passed as the argument when a button is clicked.

Run the app and you should see a dialog similar to the one below.

Notice that when you click outside the dialog, it dismisses. You can avoid this effect by adding setCancelable(false) in the builder.

B). Custom Alert Dialogs

Customization is the act of making something appear or behave differently from the default way. Alert Dialog offers us an important method, setView() that allows us to use a Layout as the View for the dialog. Such dialogs are called custom dialogs.

Moving on, create an XML layout resource file named lay_custom_dialog . We’ll use this layout for the purpose mentioned above.

Open the newly created file and paste the following code

To fix the errors about unresolved references in the “text” attribute, copy and paste the respective string resource below.

In the MainActivity.kt file, paste the following code just below showDefaultDialog() function.

Here we’ve linked the layout and created a non-cancellable dialog that can only be canceled by clicking the Ok button.

In the onCreate() method, add the following code.

We can customize it further by creating round corners. To achieve this, we’ll create a drawable resource file with a round shape then set it as the background for our layout. Create a drawable resource file named round_corners and paste the following code in it.

Remember to set this as the background of the root ViewGroup as shown below.

Before running the app we need to do the following;

  • Create a top-curved shape drawable resource named curved_view and set it as the view’s background
  • Set the color of the dialog window to transparent. This will make the round corners visible as the window background won’t be visible.

Paste the code below in the curved_view.xml file and showCustomDialog() function respectively.

The rest of the function remains the same.

Now we’re done. Run the app and you should see a dialog similar to this one

Conclusion

In this tutorial, we’ve learned how to create, customize, and use Alert Dialogs in Android. As you’ve seen, dialogs are very simple to implement. You can find the full source code for this tutorial here.

Check out the official documentation to learn more about Alert Dialogs and other types of dialogs that Android has to offer.

Peer Review Contributions by: Peter Kayere

About the author

Eric Gacoki is a 2nd-year undergraduate student pursuing computer science. He is a self-taught and solution-driven Android software developer. Currently, he’s doubling up as a co-lead in Android Stack under Developer Students’ clubs (sponsored by Google) in his university. He enjoys teaming up with all levels of developers to solve complex problems and learning from each other.

Want to learn more about the EngEd Program?

Discover Section’s community-generated pool of resources from the next generation of engineers.

Источник

Оцените статью