How To Use On Focus Change to Format Edit Text on Android Studio
Hello everyone, this post I will be talking about how to use Android Studio View.OnFocusChangeListener() to make sure users are interacting with your software in a controlled manner. Let’s think of this example; you are working on a subscription control app where you want to make sure users stick to your format while interacting with EditText.
In order to create more user friendly application, I wanted to make sure price EditText;
- Has gray color when the focus is somewhere else. (Figure 1)
- Has white color when user clicks on it. (Focus is on this View).
- If user interacted with it and left it empty, by default EditText will be set to “$0.00”.
- If EditText has value “$0.00” and user clicks, it deletes the default text and waits for user input
- If EditText doesn’t have decimal point after losing its focus, by default “.00” will be appended to the string. For example, “$50” will be “$50.00” after loosing its focus.
Using View.OnFocusChangeListener()
In order to implement this functionality we will be using View.OnFocusChangeListener(). This interface has 1 abstract method called OnFocusChange which is evoked when the focus state of a view has changed. Details of this function are;
public abstract void onFocusChange (View v, boolean hasFocus)
v -> View: The view whose state has changed.
hasFocus -> boolean: The new focus state of v.
I prefer implementing Interfaces as anonymous classes when I won’t be using the same Interface for different Views. That is why I won’t be using a separate class to implement this interface and rather Override onFocusChange inside anonymous class.
Implementation
Here is the code that I have used to implement these functionalities that I mentioned above.
If you are only interested in generic version of using OnFocusChangeListener I have code for that as well!
Now, you know how to use OnFocusChangeListener(), enjoy using it!!
I really hope this article helped you to solve something that you were looking for. If so, don’t forget to leave a clap and don’t hesitate to ask me if you have any other questions.
Happy Coding ✌🏽