Dialog and AlertDialog with custom layout on Android
In this post I will show you how to create custom dialog on Android using a layout created by us, that is, create a custom alert by adding elements such as EditText, Button, etc.
Custom alerts on Android serve to display an alert that is not a confirmation alert, since we can define a custom layout.
To achieve this we will use the
Custom alert on Android with AlertDialog
The first approach is to create an alert and add views or components. We begin by defining a Layout:
LinearLayout layout = new LinearLayout (MainActivity.this);
Then we create a component, for example, an EditText:
final EditText editTextNombre = new EditText (MainActivity.this);
We add it to the layout like this:
We can create all the necessary components and add them to the layout. Next, we create an AlertDialog:
We can set the title, the negative button and so on.
As you can see, it is a normal alert, we can even add listeners when the user clicks on the buttons that the alert has by default.
The important part that sets the custom view is as follows:
setView and pass the layout. With this we will have defined our alert, but we have not shown it yet. To show it we simply invoke
The complete code to show a custom alert on Android looks like this:
The disadvantages of this is that the layout is not 100% customized as it still retains the buttons, and it is tedious to add component by component; That is why we will see the second approach.
Custom dialog on Android using Dialog
In this mode we will use an XML layout to display it in an android dialog. The code is simpler. All we have to do is the following:
Thanks to the
setContentView method we can set a layout that will define the view for the dialog.
Then, if we have elements in our layout and want to get a reference to them, we call
findViewById but from the dialog. For example:
By the way, the layout is as follows:
I know, the custom layout is very simple, but it can be extended and all the elements can be placed inside it just like another layout.
We can add listeners to the elements and everything that is normally done as if they were normal elements obtained in an activity or fragment.
Finally, remember to show the custom alert when you need it:
The complete code looks like this:
A more complex layout of a custom alert on Android
You can add all the views that you want. Let’s see another example:
When we compile it, we have this:
In this way we can create custom dialogs and alerts on Android.
I must say that from the point of view of ui the alerts should be very simple, but sometimes a custom alert on Android is required, and that’s why I wrote this post.