How To Use On Focus Change to Format Edit Text on Android Studio

Mdayanc
2 min readMay 4, 2020

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.

Figure 1. Price EditText with no Focus

In order to create more user friendly application, I wanted to make sure price EditText;

  1. Has gray color when the focus is somewhere else. (Figure 1)
  2. Has white color when user clicks on it. (Focus is on this View).
  3. If user interacted with it and left it empty, by default EditText will be set to “$0.00”.
  4. If EditText has value “$0.00” and user clicks, it deletes the default text and waits for user input
  5. 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 ✌🏽

--

--

Mdayanc

Hey All! I am Software Engineer I love researching and experimenting new technologies and anything related to science!