Saturday, September 20, 2014

Xamarin.Android Ways to Customize Dialogs

From generic Android to Custom

On the left is Standard Android, on the right is customized. Now I am aware that it is nothing special, however I hope that readers will find the properties they need to modify in order to customize their dialogs by reading this. It is a very simple push in the right direction. I, unfortunately, am no UI designer.

Standard Android Dialog Code

First is the layout. 

Below is my layout. There are extra bits here in the EditTexts, Buttons, and Slider. You can use any layout you wish to design for dialogs, below is only an example and will not compile if you try to copy this xml right into your project. I will show you how to customize the dialog appearance and location not the controls in the dialog. That will come in a later post.

Now the Code
This code should appear in the overridden OnCreateDialog(int id) method in the activity in which you wish to show the dialog. In my case the code was found in the Details Activity. In the code below there is a const int NewGame=1 that has been previously declared. Also you will need to override the OnCreateDialog method in your class. This method override is important and if you don't override it properly your dialog won't show. So line by line. case NewGame which is equal to 1 because I previously defined it as 1. You could simply use the integer 1 and not define an integer constant this just makes it more readable as to which dialog you are working with because you may show more than one in any given activity.

This code tells the system how to build your dialog. To show it you simply call ShowDialog(NewGame) if you are on the UI Thread or RunOnUiThread(()=>ShowDialog(NewGame)) if on a background thread. An example of how you might call Show Dialog is below.

Custom Dialog

In the example if I change the root element or the first linear layout to the following. You will need to know about .9.png(9 patch).There are online tools to create them. Here is another explanation. I am no expert. I found one and edited it with paint. It is shown below.

The legbg.9.png

Custom Code

(Scroll to see comments)
After calling the show dialog code you will now see the customized dialog.

No comments:

Post a Comment