Creating a custom password text toggle for Android

Introduction to the problem

As a developer it is not uncommon that we are asked to create a login page to authenticate a user. For this purpose most of the modern applications ask for the following data:

  • Username
  • Password

Usually in android, the view components used to create a login form are TextInputLayout e TextInputEditText, because TextInputLayout offers the possibility to configure a button, that asks for a drawable resource, in order to visualize or hide a password.

However, we could want to use a text resource instead of an icon to tell the user what is the use of that button. Unfortunately android doesn’t offer such possibility at the moment so we should come up with our personalized solution.

The proposed solution

A viable solution is to create our own drawable object that extends from Drawable, that draws our desired text on it and use it to configures TextInputLayout’s button.

First, we create TogglePasswordTextDrawable extending from android Drawable:

Then we define how our text will be displayed inside the drawable creating a Paint object:

Now to effectively show the text we must specialize the draw method, which we previously got from Drawable, to adapt it to our needs. So the draw method will become like this:

If we wanted to use our class with different text resources we can pass the text as constructor parameter:

With this we have finished the creation of our custom drawable class.

The last step we have to do is to define a list that comprehend the two possible states in which the toggle could be, and then assign this list to the passwordVisibilityToggleDrawable TextInputLayout property.

The following gif shows the final result.

Now you can enjoy your password text toggle.

Thank you for reading.