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.
Источник
Password Visibility Toggle — Android Support Library, revision 24.2.0
Здравствуйте! Предлагаю вниманию читателей перевод статьи об обновлении Android Support Library и одном немаловажном ее новом компоненте Password Visibility Toggle . Оригинал статьи можно найти здесь.
Считаю, что Password Visibility Toggle довольно интересный инструмент, причем довольно простой, который заслуживает отдельного внимания, поэтому прошу под кат.
От себя хочу добавить, что текущее обновление Support Library считается одним из самых масштабных: разделение на несколько маленьких модулей — несомненный плюс, который поможет уменьшить вес вашего .apk файла; большое обновление API; куча deprecations ну и немножко bugfixes нам принесли.
Android Support Library была недавно обновлена с весьма интересными изменениями. Я обратила внимание на Password Visibility Toggle не случайно: буквально несколько дней назад я пыталась реализовать этот функционал в своём рабочем проекте без использования каких-либо библиотек (между прочиим, Lisa Wray разработала прекрасную либу).
Я восхваляла это в твиттере.
Естественно, это было одной из первый вещей, которую я использовала, поскольку мне нужно было немедленно обновить свой проект.
Здесь очень базовый туториал как с этим работать.
Первый шаг
Первый и самый очевидный — это, конечно же, обновить версию Support Library до 24.2.0. Надеюсь, у тебя версии зависимостей прописаны в extra properties. Если да, то это означает, что тебе нужно поменять версию лишь в ОДНОМ месте. Если нет, то тебе прийдется изменять Gradle файл столько раз, сколько версия встречается.
Далее
Следующим шагом будет создание TextInputEditText и задание inputType одним из следующих вариантов: textPassword, numberPassword, textVisiblePassword либо textWebPassword. Я пробовала все 4 типа и заметила, что иконка видимости появляется на всех кроме textVisiblePassword варианта, что довольно очевидно, поскольку эта опция изначально задает видимость пароля по умолчанию.
Этот же код на gist.github автора.
Есть 5 XML аттрибутов связанных с password visibility toggle.
- passwordToggleContentDescription позволяет нам установить строку в качестве content description
- passwordToggleDrawable позволяет нам установить другую иконку, кроме значка видимости visibility toggle icon
- passwordToggleEnabled позволяет нам определить хотим ли мы что бы пароль был переключаемый. Мне кажется, что это должно быть установлено только если ты специально не хочешь сделать поле переключаемым
- passwordToggleTint позволяет нам окрасить значок в какой-либо цвет. Так же работает с custom drawable
- passwordToggleTintMode позволяет нам задать так называемый режим смешивания, в котором мы можем применить оттенок для фона.
Как обыкновенный Android UI компонент в XML, так же возможно реализовать это (passwordToggleContentDescription, passwordToggleDrawable, passwordToggleEnabled, passwordToggleTint and passwordToggleTintMode) непосредственно кодом: необходимо создать TextInputEditText и вызвать один из этих методов.
Замечания
После того, как я это заимплементила, я ожидала, что иконка видимости будет по умолчанию перечёркнута(ссылка на мой твит выше). Твит ниже от Nick Butcher и даже либа от Lisa Wray демонстрирует тоже самое. Я была несколько разочарована попробовав ее и обнаружив, что по-умолчанию изменение состояния видимости значка было лишь его незначительное затемнение вместо зачеркивания. Это не достаточно очевидно, по-моему мнению, так как это могло привести к заблуждению, особенно таких пользователей как я, который уже пробовали эту фичу на других платформах и ожидали такого же поведения. Мне необходимо было создать кастомный StateListDrawable и задать в passwordToggleDrawable XML аттрибуте тип эффекта, которого я хочу достигнуть.
Твит о Password Visibility Toggle от Nick Butcher.
Некоторые слова специально не переводил, так как считаю, что они могут исказить восприятие разработчика. Большинство слов уже считается нормой в нашей работе.
Если есть предложения по улучшению качества перевода либо что-то звучит просто несуразно — критика приветствуется.
Источник
Visible password with TextInputLayouts passwordToggleEnabled
I am using a TextInputLayout with the new function from the Support Library: passwordToggleEnabled. This gives a nice «eye»-icon that lets the user toggle password visibility on and off.
My question is if there is a way to use this functionality but start with password visible?
The toggle looks similar to this:
I have not found a way to do this in xml, and not a way to manually toggle the visibility after the view is rendered. If I set the input type of the EditText to textVisiblePassword, the toggle is not shown. If I do it in code using for instance mPasswordEditText.setTransformationMethod(null); the password is shown but the toggle is gone and the user can’t hide the password again. I know I can do it all manually but just wondering if I can make it work with the new magic toggle
9 Answers 9
Easiest way is below Another solution is at last of this answer
Now let me explain the answer
While looking into code of TextInputLayout.java I found that, there is a layout design_text_input_password_icon.xml which is being added to TextInputLayout.java . Below is that code
Now next target was to find design_text_input_password_icon.xml and lookup id of the toggle view. So found the layout design_text_input_password_icon.xml here and it has written as
I found the id text_input_password_toggle of that view and now everything was easy to just find that view in it’s viewgroup and perform action on that.
Another solution would be to iterate childs of TextInputLayout and check if it is CheckableImageButton and then perform click on it. By this way there would not be dependancy on id of that view and if Android changes the id of view, our solution will still work. (Although they do not change id of a view in normal cases).
Where findViewByClassReference(View rootView, Class clazz) original utility class is defined as below
Источник
Android edittext password toggle
This library is deprecated now as there is an official way to use the password toggle with the TextInputLayout (inside the support library starting with version 24.2.0 ).
For more information check the official docs.
A simple extension to the standard Android EditText which shows an icon on the right side of the field and lets the user toggle the visibility of the password he puts in.
Support-library versions 24.2.0 and upwards now have built-in functionality to show an eye icon and toggle password visibility (For more info see docs). You can nevertheless still use this lib, maybe because you want some of the features that the built-in approach does not have.
How does it look like?
For a complete sample you can check out the sample project provided within.
In short: Just include the PasswordEditText instead of the standard EditText and you are good to go.
You can also wrap PasswordEditText inside a TextInputLayout to get a material design moving label on top:
Note: be sure to include the design library to use TextInputLayout . (for more details see sample )
You can also use TextInputLayout to achieve an even prettier setError() dialog using setErrorEnabled(true) on the outer TextInputLayout and then calling setError() on it. This underlines the text and shows an error message underneath the text.
You can add your own custom icons which are shown on the right side of the EditText .
Do this by first adding the custom namespace to your root layout, e.g.:
After that you can add the icons with the attributes app:pet_iconShow and app:pet_iconHide :
You can also set toggle the monospace Font inside the PasswordEditTexts with app:pet_nonMonospaceFont :
Another customization is to just toggle the visibility of the password when the icon is hovered with app:pet_hoverShowsPw :
If you do not like the alpha, that is set to all the icons, you can disable it using app:pet_disableIconAlpha
For a working example of the different customizations check out the activity_main.xml inside the sample project.
The library is available from jcenter() , so all you need to do is include it in your apps build.gradle :
Alternatively you can use jitpack.io : More info here: https://jitpack.io/#maksim88/PasswordEditText
If you have any questions feel free to open a github issue with a ‘question’ label
Licensed under the MIT license. See LICENSE.
About
A custom EditText with a switchable icon which shows or hides the password
Источник