How to use EditTextPreference as a masked Password text field?

前端 未结 5 1873
感动是毒
感动是毒 2021-02-04 23:51

I have a very simple question:
I have a EditTextPreference dialog which I want to use for getting the user\'s password and I want it to be masked.

How c

5条回答
  •  我在风中等你
    2021-02-05 00:16

    You can do it with the code below. HOWEVER, I still haven't figured out how to do the PASSWORD_TOGGLE thing. Doesn't work by just defining app:endIconMode="password_toggle" Can someone help with that?

    The ANSWER: The "EditTextPreference" field "db_pwd" has the following defined:

    android:inputType="textPassword"
    

    The latest Kotlin rev code:

    class SettingsFragment : PreferenceFragmentCompat() {
    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        setPreferencesFromResource(com.unified.helloworld.R.xml.my_preferences, rootKey)
        val pwdPref =
            findPreference("db_pwd")
        if (pwdPref != null) {
            pwdPref.summaryProvider = SummaryProvider {
                val getPassword: String =
                    PreferenceManager.getDefaultSharedPreferences(context)
                        .getString("db_pwd", "Not set")!!
    
                // Return "Not set" else return password with asterisks
                if (getPassword == "Not set") {
                    getPassword } else { setAsterisks(getPassword.length) }
            }
    
            // Set type as password and set summary with asterisks
            pwdPref.setOnBindEditTextListener(
                OnBindEditTextListener { editText ->
                    editText.inputType =
                        InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_VARIATION_PASSWORD
                    pwdPref.summaryProvider = SummaryProvider { setAsterisks(editText.text.toString().length) }
                })
        }
    }
    
    // Return the password in asterisks
    private fun setAsterisks(length: Int): String {
        val sb = java.lang.StringBuilder()
        for (s in 0 until length) {
            sb.append("*") }
        return sb.toString() }
    }
    

提交回复
热议问题