Reputation: 21
I am trying to include an EditTextPreference
for a password, and want to hide the characters and show asterisks, but not able to do it.
this is my preference.xml file:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.preference.PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory
android:title="Scenes">
<DropDownPreference
android:key="scenario"
android:title="Select scene"
android:summary="%s"
android:entries="@array/scenarios"
android:entryValues="@array/scenarios_values" />
</PreferenceCategory>
<PreferenceCategory
android:title="Demo">
<SwitchPreference
android:key="connect_on_startup"
android:title="Auto Connect"
android:defaultValue="false"
android:summary="Connect automatically at startup" />
<EditTextPreference
android:title="UserName"
android:key="username"
android:summary="Please provide your Username"
android:maxLines="1"
android:singleLine="true">
</EditTextPreference>
<EditTextPreference
android:inputType="textPassword"
android:title="Password"
android:key="password"
android:summary="Please provide your Password"
android:password="true" />
</PreferenceCategory>
What can I be doing wrong? Thanks!
Upvotes: 1
Views: 868
Reputation: 169
In Androidx this must be done with the following two step process
EditTextPreference passwordEditText = (EditTextPreference)findPreference("password");
passwordEditText.setOnBindEditTextListener(new androidx.preference.EditTextPreference.OnBindEditTextListener() {
@Override
public void onBindEditText(@NonNull EditText editText) {
editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
}
});
passwordEditText.setSummaryProvider(new Preference.SummaryProvider() {
@Override
public CharSequence provideSummary(Preference preference) {
int valueSize= PreferenceManager.getDefaultSharedPreferences(getContext()).getString(preference.getKey(),"").length();
String newSummary="";
for (int i = 0; i < valueSize; i++) {
newSummary+="*";
}
return newSummary;
}
});
Upvotes: 1
Reputation: 8968
If you need to hide text shown in the summary, it should be done outside of the xml file. You probably have code template from android studio that contains implementation of Preference.OnPreferenceChangeListener
. Inside of it there is callback method that is called when settings are changed. By default it changes summary to the incoming value:
preference.setSummary(stringValue);
Instead of it, you need to check if the preference is your password and skip setting the summary, something like this:
if ("password".equals(preference.getKey())) {
preference.setSummary("***");
} else {
preference.setSummary(stringValue);
}
Upvotes: 0
Reputation: 10547
android:password="true"
is deprecated you should use android:inputType="textPassword"
instead.
Upvotes: 0