Afew days ago, I was working on a project where I had to implement form validation on textInputLayout
and textInputEditText
using data binding.
Unfortunately, there is not enough documentation available for that.
Finally, I achieved what I wanted through some research and experiments. This is what I wanted to achieve:
So I know there are many developers who want the same actions and user-friendly behaviour on forms.
Let’s get started.
What Are We Going to Use?
- Kotlin
- Data binding
- Material library
I am going to break the whole project down into steps to make it easy for you to understand.
Set up the initial project and enable data-binding from build.gradle(:app)
by adding this line under the android{} tag:
dataBinding{
enabled true
}
To use textInputLayout
and textInputEditText
, you need to enable Material support for Android by adding this dependency in build.gradle(:app)
:
implementation 'com.google.android.material:material:1.2.1'
Let’s make a layout of our form. I am making it simple because my goal is to define the core functional part of this feature rather than designing the layout.
Roadmap to Becoming a Successful Android Developer
I made this simple layout:
Here is the activity_main.xml
:
Our layout is ready. Let’s do some coding now.
If you look at the GIF of the final app (earlier in the article), you will see how errors are showing and hiding accordingly as the conditions become true.
This is because I have bound each text field with TextWatcher
, which continuously calls as a user types something in the field.
Here, I have made a class inside MainActivity.kt that inherits from TextWatcher
:
Don’t worry about view
, which is passing in the constructor of the class. I will define it later.
Here is the main part. Each text field has some conditions that need to be true before submitting the form. So, the code for each text field condition is as follows:
Now it’s time to bind each text field with the textWatcher
class that we created earlier:
But how would TextFieldValidation
know which text field to bind? Scroll up and have a look at the comment that I have mentioned inside the TextFieldValidation
method:
// checking ids of each text field and applying functions accordingly.
Notice I am passing a view inside the constructor of TextFieldValidation, the class that is responsible for segregating each text field and applying each of the methods above like this:
Your final MainActivity.kt
would look like this:
You can download the complete source code for this project below:
I hope you have learned something new. Stay tuned for more articles like this. Happy coding!
Top comments (0)