2016-09-08 2 views
1

У меня есть легкая проблема, но я не могу найти решение. Позволяет создать страницу настроек, созданную в студии Android. И вот одно поле - пароль.Скрыть пароль на экране настроек

<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" /> 

Нет проблем с вводом данных со звездочками. Но проблема в том, что я вижу, сохраненные пароли на экране:

enter image description here

Как я могу это скрывать?

спасибо.

+0

Почему вы используете EditTextPreference? –

+1

Вы также хотите скрыть звездочки? – hrskrs

+0

Не могли бы вы объяснить, где вы видите пароль на экране, вы имеете в виду при наборе текста? – martinstoeckli

ответ

1

Я решил проблему с помощью OnPreferenceChangeListener который вызывается перед отображением предпочтения и при его изменении. Я пользуюсь возможностью, чтобы установить измененную версию пароля в сводке, путем преобразования текста в строку со звездами.

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; 

} 
+0

Отлично !!! Спасибо. –

0

использование этого

<EditTextPreference 
    android:inputType="textPassword" 
    android:key="@string/key" 
    android:summary="@string/summary" 
    android:title="@string/title" /> 

андроид: inputType, как вы хотите

благодаря

+0

Здравствуйте, у меня есть android: inputType = "textPassword", но у меня не проблема при наборе текста, thats allrigt. У меня проблема, что я могу видеть простой пароль после сохранения на экране настроек. –

+0

Вы хотите установить пароль на экране настроек в формате пароля? –

+0

Я не хочу видеть сохраненный пароль в виде обычного текста на экране настроек. Когда я набираю пароль, я хорошо работаю. –

0

общественного класса PasswordPreference расширяет DialogPreference

{

private String password; 
private EditText passwordEditText; 
private EditText confirmEditText; 

public PasswordPreference(Context context, AttributeSet attrs, int defStyle) { 
    super(context, attrs, defStyle); 

    init(context, attrs); 
} 

public PasswordPreference(Context context, AttributeSet attrs) { 
    super(context, attrs); 

    init(context, attrs); 
} 

private void init(Context context, AttributeSet attrs) { 
    setDialogLayoutResource(R.layout.confirm_password); 

    passwordEditText = new EditText(context, attrs); 
    confirmEditText = new EditText(context, attrs); 

} 

private void detachView(View view, View newParent) { 
    ViewParent oldParent = view.getParent(); 
    if (oldParent != newParent && oldParent != null) 
     ((ViewGroup) oldParent).removeView(view); 
} 

@Override 
public void onBindDialogView(View view) { 
    detachView(passwordEditText, view); 
    detachView(confirmEditText, view); 

    LinearLayout layout = (LinearLayout) view.findViewById(R.id.linearLayout); 
    layout.addView(passwordEditText); 
    layout.addView(confirmEditText); 

    passwordEditText.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { 

     } 

     @Override 
     public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { 

     } 

     @Override 
     public void afterTextChanged(Editable editable) { 
      verifyInput(); 
     } 
    }); 

    confirmEditText.addTextChangedListener(new TextWatcher() { 
     @Override 
     public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) { 

     } 

     @Override 
     public void onTextChanged(CharSequence charSequence, int i, int i2, int i3) { 

     } 

     @Override 
     public void afterTextChanged(Editable editable) { 
      verifyInput(); 
     } 
    }); 

    String oldPassword = getSharedPreferences().getString("password", ""); 
    passwordEditText.setText(oldPassword); 
    confirmEditText.setText(oldPassword); 
} 

private void verifyInput() { 
    String newPassword = passwordEditText.getText().toString(); 
    String confirmedPassword = confirmEditText.getText().toString(); 

    boolean passwordOk = false; 
    if (newPassword.equals(confirmedPassword)) { 
     passwordOk = true; 
     password = newPassword; 
    } 

    AlertDialog dialog = (AlertDialog) getDialog(); 
    if (dialog != null) 
     dialog.getButton(AlertDialog.BUTTON_POSITIVE).setEnabled(passwordOk); 
} 

@Override 
protected void onDialogClosed(boolean positiveResult) { 
    super.onDialogClosed(positiveResult); 

    if (!positiveResult) 
     return; 
    persistString(password); 
} 

}

<com.abax.applocker.PasswordPreference 
     android:background="@color/white" 
     android:inputType="numberPassword" 
     android:key="password" 
     android:password="true" 
     android:summary="Edit the Unlock password" 
     android:title="Edit Password" /> 

используют эту

1

спасибо всем, в настоящее время я использовал "исправление", которое скрывает значение пароля. Я попробую заменить его в будущем. Исправление в том, что я просто удалить показ пароль:

bindPreferenceSummaryToValue(findPreference("username")); 
//bindPreferenceSummaryToValue(findPreference("password")); 
bindPreferenceSummaryToValue(findPreference("ip")); 
bindPreferenceSummaryToValue(findPreference("port")); 
Смежные вопросы