1. 程式人生 > >How To Create Custom Dialog In Android With Validation

How To Create Custom Dialog In Android With Validation

Let’s learn how to create custom dialog in android and while we are at it, let us also do simple validation of the data the user entered before clicking the OK button! What is an alert dialog in android? It is a small window that asks a user to make a decision or enter more information in an app. You have probably seen a lot of them if you have used android apps in your smartphone. Anyway, the reason why I am showing you how to create custom dialog is because sometimes you may wish to have a different looking dialog box than what comes with your sdk and more importantly, you may wish to validate the data – without using your own custom dialog, it can be tricky …but not anymore! Let us take a look!

how to create custom dialog in android

Now, after you enter some crappy data and attempt to submit it, we can perform some validation to make sure that you did the RIGHT thing! You cannot trust everyone online after all! So, it will say something like this if there are errors in your entries and you must fix them before moving on!

How To Create Custom Dialog In Android

That being said, I think it is time to see some code – I agree with you on that!

How To Create Custom Dialog In Android – The Sample Code

Step One

As I mentioned earlier, you have to create your custom xml layout that will contain the Edit Text components with the custom button shown above. This implies that we will not be using the default layout provided by the Dialog class and we then override the functionality which includes the setting of the OK and Cancel actions – this will actually enable us to validate our data whenever a user tries to submit silly information.

name_and_email.xml

12345678910111213141516171819202122232425262728293031323334353637383940 < ?xml version="1.0"encoding="utf-8"?>< LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent"android:background="@drawable/background_tile">< EditText android:layout_width="500dp"android:layout_height="50dp"android:hint="@string/name_hint"android:ems="15"android:inputType="textNoSuggestions|textCapWords"android:textSize="20sp"android:capitalize="words"android:typeface="sans"android:id="@+id/follower_name"android:layout_gravity="center_horizontal"android:layout_margin="20dp">< EditText android:layout_width="500dp"android:layout_height="50dp"android:inputType="textNoSuggestions|textEmailAddress"android:ems="15"android:textSize="20sp"android:capitalize="none"android:hint="@string/email_hint"android:id="@+id/follower_email"android:layout_margin="20dp"android:layout_gravity="center_horizontal">< Button android:id="@+id/submit"android:layout_width="200dp"android:layout_height="70dp"android:layout_margin="20dp"android:text="@string/submit"android:layout_gravity="center_horizontal">

NOTE Always remember to create your xmls correctly (do not copy and paste the above code without correcting the component names like button must start with an upper case) – my syntax highlighter sucks and I am planning to look for a better one!
Now, we have created our custom dialog layout that the users will see and the next thing is to create a java class that will do the displaying and validation of the data. Without much ado, here we have it!

CUstomDialogActivity.java

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 /** * @author Elisha Chirchir - Simple Developer * @since 1.0.0 2014 */publicclassCustomDialogActivityextendsActivity{@OverridepublicvoidonCreate(Bundle saveInstanceState){super.onCreate(saveInstanceState);setContentView(R.layout.main);//call the method to display the custom dialogdisplayDialogWindow();}/**    * This method creates an alert dialog using the AlertDialog Builder class and     * also sets the theme of your choice.     * It then inflates a custom dialog which completely ignores the OK and NO buttons    * Finally performs validation before dismissing the dialog window (if correct input is given)    */publicvoiddisplayDialogWindow(){finalAlertDialog.Builder loginDialog=newAlertDialog.Builder(newContextThemeWrapper(this,android.R.style.Theme_DeviceDefault_Light_Dialog));LayoutInflater factory=LayoutInflater.from(this);finalViewf=factory.inflate(R.layout.name_and_email,null);loginDialog.setTitle("Please enter your name and email");loginDialog.setView(f);Button submit=(Button)f.findViewById(R.id.submit);submit.setOnClickListener(newView.OnClickListener(){@OverridepublicvoidonClick(Viewv){Validator validator=newValidator();EditText full_name=(EditText)f.findViewById(R.id.follower_name);EditText email_address=(EditText)f.findViewById(R.id.follower_email);Stringfollower_name=full_name.getText().toString();Stringfollower_email=email_address.getText().toString();booleanvalidName=validator.validateFullName(follower_name);booleanvalidEmail=validator.validateEmail(follower_email);if(!validName||!validEmail){if(!validName){full_name.setError("** Please enter a valid name");}if(!validEmail){email_address.setError("** Please enter a valid email address");}}else{//send data to the database//basically like dismissing the dialog window here (you can start a new intent) }});loginDialog.show();}}

Believe it or not, this will do the job shown above. You can then add your own background image/tiling to pretty this baby up a little more if you want.

You learn how to create a custom dialog in android for several reasons; perhaps to avoid conformity or just because you want to do something that default dialog do not provide – like in our case, validating data before dismissing the window. This also means if the data is wrong, you want to keep the window open so the user can correct the data entered before re-submitting it. The other possible reason could be just being creative and I will tell you something for sure; it goes a long way!

You can add anything you want into your custom xml – that is why it is custom!

So, that being said, I would like to call it a day here! If you have any questions, please do not hesitate to ask me because I would love to hear from you! If you also liked this post, please share it with your friends using the buttons below and drop me some comments. Like I have always tried to say, I would hate to close this post without directing you to the birthplace of ‘How to create custom dialog in android’ – the well written documentation.

Thank you for stopping by and please see you soon!