Sometimes you want to show your users a dialog that contains more than just text and buttons. In those cases the pre-defined AlertDialog
that come with Android will need some adjustment. Read here how to do that.
First of all we need an Alert Dialog Builder as always when it comes to creating dialogs in Android. If you want to go with backwards compatibility you should use the one that can be found inside the Android.Support.V7.App
class, but you don’t necessarily need to. Instead of simply adding a title and a message we now have the chance to inflate our custom layout and set it as the dialog’s view.
1 2 3 4 |
// Create a dialog using the Builder var builder = new Android.Support.V7.App.AlertDialog.Builder(this); var dialogView = LayoutInflater.Inflate(Resource.Layout.AddHomeControlSystemDialog, null); builder.SetView(dialogView); |
Once the view is attached to the dialog we can manipulate it. We can access its elements by calling FindViewById
from the dialogView
.
1 2 3 4 |
// Access the custom view dialogView.FindViewById(Resource.Id.etName).Text = "Pumping Code"; dialogView.FindViewById(Resource.Id.etAddress).Text = "www.pumpingco.de"; dialogView.FindViewById(Resource.Id.spBrand).SetSelection(4); |
Of course you can still attach buttons and event hanlders to your dialog or set a title, like you are used to it when working with the pre-definded alert dialog.
1 2 3 4 5 6 7 |
// Set title builder.SetTitle(Resource.String.dialog_title); // Add button builder.SetPositiveButton(Android.Resource.String.Ok, (sender, e) => { Toast.MakeText(this, "Hello", ToastLength.Short).Show(); }); |
Don’t forget to show the dialog with builder.Show()
and proudly present your first custom dialog to your users!
2 Comments
Dwight Ross · July 18, 2016 at 06:18
The buttons work fine but not the Edittext, I cannot set or get their value, I have been trying for almost an entire day.
Dwight Ross · July 18, 2016 at 06:34
Update: I got it (Editext=customView.FindViewById(Resource.Id.someview);)