Search code examples
androidandroid-preferences

Hide password on settings screen


I have easy problem, but I cannot find solution. Lets have settings page generated over Android studio. And here is one field - password.

<EditTextPreference
    android:defaultValue="@string/pref_default_display_password"
    android:inputType="textPassword"
    android:key="password"
    android:maxLines="1"
    android:selectAllOnFocus="true"
    android:singleLine="true"
    android:password="true"
    android:title="@string/pref_title_display_password" />

There is no problem with input which is with asterisks. But problem is, that I see saved password on screen:

enter image description here

How can I hide it?

Thank you very much.


Solution

  • I solved the issue using OnPreferenceChangeListener which is called before the preference is displayed and when it is changed. I take the opportunity then to set a modified version of the password in the summary, by converting the text to string with stars

    Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            String stringValue = value.toString();
            ...
            if (preference instanceof EditTextPreference){
                // For the pin code, set a *** value in the summary to hide it
                if (preference.getContext().getString(R.string.pref_pin_code_key).equals(preference.getKey())) {
                    stringValue = toStars(stringValue);
                }
                preference.setSummary(stringValue);
            }
            ...
            return true;
        }
    };
    
    String toStars(String text) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < text.length(); i++) {
            sb.append('*');
        }
        text = sb.toString();
        return text;
    
    }