1. 程式人生 > >Handling & Validating User Input (& More) with sauciness in Android with Java

Handling & Validating User Input (& More) with sauciness in Android with Java

Things you’ll need

  • Design Support Library (TextInputLayout & TextInputEditText)
  • ValidComponent Annotation (We’ll create it)
  • Component Validator & Other Helper Classes (We’ll create these well)

Why you’re going to need them

The design support library’s components provide a nice & pretty way of validating edit text input fields. The EditTexts

that we are going to validate is just an example; By annotating the proper fields and implementing the proper interfaces you can validate anything, even non-view components.

We are going to subclass TextInputEditText to create a a ‘AutoValidatedTextInputEditText’ which is going to present the user with errors when he types, or when focus is lost. The auto validated components get loaded up with TextValidators that do the actual validation work of course.

The @ValidComponent annotation is going to mark any Object’s (in our case, an Activity’s) fields which we can check on runtime via Reflection (with the ComponentValidator) to check if they are valid. We are going to return null if there is no invalid component or, the component otherwise. These AutoValidatedTextInputEditText

components can be requested to be brought to focus afterwards, so that the user can correct his mistakes.

The Implementation

All the code provided in this blog post is available under the MIT license.

That’s everything. If you want to be able to on-demand validate any object, you should also include these ones in your project:

A Simple Example

This example showcases what we made till now, as well as a case where a user does not need to input text directly (he can pick a date from the picker, or type it out manually if he closes the picker).

Let’s suppose that you’ve got some kind of activity (that’s basically a form with a submit button). You want to add the ui components and then mark only those you want to be able to validate on demand.

Notice that even if you mark some other field that’s not supported by the ComponentValidator, it’s just going to be ignored & your app is not going to crash.

Thanks for reading, be sure to clap if you liked this implementation and comment if you’ve thought about some improvement or refactoring!

Special thanks to my good and experienced C# Developer friend Nick ‘Elfocrash’ Chapsas for providing guidance & helping me with refactoring and best practises.