Show a custom dialog in your Xamarin Android app

Sometimes you want to show your users a dialog that contains more than just text and buttons. In those cases the pre-defined <a href="http://developer.android.com/reference/android/app/AlertDialog.html">AlertDialog</a>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 theAndroid.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.

<code class="language-clike">// 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`.

// 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.

<code class="language-clike">// 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!