Search code examples
androidandroid-preferencesandroid-jetpack

EditTextPreference does not mask password even with android:inputType="textPassword"


I have following code

<androidx.preference.PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:android="http://schemas.android.com/apk/res/android">

        <EditTextPreference
            app:key="pref_password"
            app:title="Password"
            app:iconSpaceReserved="false"
            app:dialogTitle="Password"
            android:inputType="textPassword"/>

</androidx.preference.PreferenceScreen>

But the edit text field is not masked with dots even with android:inputType="textPassword"

I am using androidx. Anyone please help

Update

I tried following as a commenter suggested, but no luck

<EditTextPreference
            android:key="pref_password"
            android:title="Password"
            app:iconSpaceReserved="false"
            android:dialogTitle="Password"
            android:inputType="textPassword"/>

Solution

  • Setting attributes directly on the EditTextPreference doesn't work with the AndroidX library - since an EditTextPreference isnt' an EditText, and shouldn't work as such. Instead you should use an OnBindEditTextListener to customize the EditText when it is displayed. (need androidx.preference:preference v1.1.0 and higher)

    See the settings guide for more information

    edit with code:

    Java:

    EditTextPreference preference = findPreference("pref_password");
    
    if (preference!= null) {
        preference.setOnBindEditTextListener(
                new EditTextPreference.OnBindEditTextListener() {
                    @Override
                    public void onBindEditText(@NonNull EditText editText) {
                        editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    }
                });
    }
    

    Kotlin:

    val editTextPreference: EditTextPreference? = findPreference("pref_password")
    
            editTextPreference?.setOnBindEditTextListener {editText ->  
                editText.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
            }