I've resolved my issue by extending the EditTextPrefence
class and overriding setText
and getText
this is based on the answer I found here
package com.example.overrides;
import android.content.Context;
import android.preference.EditTextPreference;
import android.util.AttributeSet;
public class SanitizedEditTextPreference extends EditTextPreference {
public SanitizedEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
public SanitizedEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public SanitizedEditTextPreference(Context context) {
super(context);
}
@Override
public String getText() {
String value = super.getText();
return StringUtil.sanitize(value);
}
@Override
protected void onSetInitialValue(boolean restoreValue, Object defaultValue) {
super.setText(restoreValue ? getPersistedString(null) : (String) defaultValue);
}
@Override
public void setText(String text) {
if (StringUtil.isStringBlank(text)) {
super.setText(null);
return;
}
super.setText(StringUtil.sanitize(text));
}
}
I simplified my previous code to:
/**
* A preference value change listener that updates the preference's summary
* to reflect its new value.
*/
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
// For list preferences, look up the correct display value in
// the preference's 'entries' list.
ListPreference listPreference = (ListPreference) preference;
int index = listPreference.findIndexOfValue(stringValue);
// Set the summary to reflect the new value.
preference.setSummary(
index >= 0
? listPreference.getEntries()[index]
: null);
} else if (preference.getKey().equals("text_default_album")) {
stringValue = StringUtil.sanitize(stringValue);
preference.setSummary(stringValue);
} else {
// For all other preferences, set the summary to the value's
// simple string representation.
preference.setSummary(stringValue);
}
return true;
}
};
and in the pref.xml
file it is used like:
<com.example.overrides.SanitizedEditTextPreference
android:key="text_default_album"
android:title="@string/pref_title_default_album"
android:defaultValue="@string/pref_default_album"
android:selectAllOnFocus="true"
android:inputType="text"
android:capitalize="none"
android:singleLine="true"
android:maxLines="1" />