How to Toggle Password Visibility in Android?
As we know that toggling means switching between the two different options by pressing a single button. So In this article, we would be seeing how to change the password visibility by pressing a single button (here it would be eye button), ie with an input of password type, we can also enable an icon, that can show or hide the text that the user is typing. To implement this project we would be using the TextInputLayout(child of Linear Layout), which is a design component that comes with the Android Material Design Library.Since we would be entering the password, TextInputEditText will be used instead of normal EditText, since TextInputEditText is a sub-class of EditText and TextEditText is a child of TextInputLayout.There are five XML attributes associated with the password visibility toggle.
- passwordToggleEnabled: This attribute has its value either true or false, so when we want the password to be toggleable, we should assign this attribute the true value.
- passwordToggleTint: allows giving the color the visibility toggle icon.
- passwordToggleTintMode: allows giving different background modes to the toggle icon.
- passwordToggleDrawable: allows us to give a different icon instead of the default eye image to the toggle icon.
- passwordToggleContentDescription: Allows us to give the description to the toggle icon.
A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
Step by Step Implementation
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Working with the activity_main.xml file
Now go to the activity_main.xml file which represents the UI of the application. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.
Step 3: Working with the build.gradle (App Level File)
Import the dependency on the material components in the dependency section.
Step 4: Working with the MainActivity.kt file
Go to the MainActivity.kt file, and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Since there is no logic that needs to be executed in this project, MainActivity does not contain any code.