简体   繁体   中英

How to format value in onPreferenceChangeListener before saving?

I have an EditTextPreference in my PreferenceScreen in the field i have to save the user have to input a valid URL and as that url will be used for retrofit calls i have to format it properly.

So i've created a onPreferenceChangeListener where initially i check if the url insert is valid and then i'm formatting it.

The issue is that once the user press ok the formatted value is not saved, no value is saved at all.

Here is my listener:

private fun String.formatURL(): String {
    var url = this

    if (!this.startsWith("http")) {
        url = "http://$url"
    }

    if (!url.endsWith("/")) {
        url = "$url/"
    }

    return url
}

editPref?.onPreferenceChangeListener =
    Preference.OnPreferenceChangeListener { preference, newValue ->
        val url = newValue.toString()
        if (Patterns.WEB_URL.matcher(url).matches()) {
            preference.sharedPreferences.edit().putString(preference.key, url.formatURL())
            false
        } else {
            customSnack(requireView(), "URL del server non valido!", true)
            false
        }
    }

note that OnPreferenceChangeListener return true / false if value can be stored or not. you are returning false even whe URL matches pattern. you should return true then

    if (Patterns.WEB_URL.matcher(url).matches()) {
        preference.sharedPreferences.edit().putString(preference.key, url.formatURL())
        true // proper URL, storing, handled
    } else {
        customSnack(requireView(), "URL del server non valido!", true)
        false
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM