Android 如何确保保存时已清除SharedReference

Android 如何确保保存时已清除SharedReference,android,Android,在Android应用程序中,我让用户通过运行一个扩展PreferenceActivity的类来编辑他的偏好。 在res\xml中,我有一个文件-preferences.xml-其中包含用户可以配置哪些字段的xml描述。比如用户名和密码。示例代码段: <EditTextPreference android:name="User Name" android:summary="Name in Your Name/Company format" android:defaultValue="" an

在Android应用程序中,我让用户通过运行一个扩展PreferenceActivity的类来编辑他的偏好。 在res\xml中,我有一个文件-preferences.xml-其中包含用户可以配置哪些字段的xml描述。比如用户名和密码。示例代码段:

<EditTextPreference android:name="User Name"
android:summary="Name in Your Name/Company format"
android:defaultValue="" android:title="Login name" android:key="userName" 
android:id="@+id/userName"/>

<EditTextPreference android:name="Password"
android:summary="Your web password" android:defaultValue=""
android:title="Login password" android:password="true" android:key="userPassword" 
android:id="@+id/userPassword"/>

事情按预期进行。从我的主应用程序代码中,我可以访问用户配置的值

有一件事我希望得到一些关于如何处理的好建议:删除首选项值中的前导空格和尾随空格

由于用户错误或键盘应用程序的帮助,有时用户会在EditTextPreferences字段中输入额外的空白字符。作为第一个或最后一个字符

我更希望在用户退出PreferenceActivity之前删除这些明显的键入错误。 我想获得清理用户偏好的好方法的建议。

只需对用户提供的值使用
String.trim()
,然后将其保存到prefs。trim()方法从输入字符串的前面和结尾删除所有空白字符


()

继Ollie C的评论之后,onDialogClosed当前的EditTextPreference代码如下所示:

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

    if (positiveResult) {
        String value = mEditText.getText().toString();
        if (callChangeListener(value)) {
            setText(value);
        }
    }
}
这将使用原始值调用更改侦听器。与其修改setText,我建议您在子类中执行以下操作:

@Override
protected void onDialogClosed(boolean positiveResult)
{
    String text = getEditText().getText().toString();
    getEditText().setText(text.trim());

    super.onDialogClosed(positiveResult);
}

对所有用户输入调用trim()是否有效?谢谢您的建议。我希望你能为我澄清一些事情。因为我使用的是PreferencesActivity,所以我不会主动保存每个首选项值。保存过程必须以某种方式隐藏在PreferencesActivity和xml文件组合的抽象层中。那么,您建议我如何访问首选项的每一个值来执行String.trim()?啊,我明白了,很抱歉我错过了。我将扩展EditTextPreference以构建您自己的TrimmedEditTextPreference,并重写setText()以执行trim()以尝试您的建议我创建了一个新类:公共类TrimmedEditTextPreference扩展了EditTextPreference。它现在只包含三个构造函数。我还没有开始研究setText()。在my preferences.xml中,我将其中一个条目的类型从EditTextPreference更改为TrimmedEditTextPreference。当我在模拟器中运行应用程序并打开首选项时,它将强制关闭。在logcat中,我在loader dalvik.system中获得java.lang.ClassNotFoundException:android.preference.TrimmedEditTextPreference。PathClassLoader@44dac878In您需要对类使用完全限定引用的XML,如com.blah.trimmeditTextPreference您的建议对我有用。谢谢我所做的只是重新创建三个构造函数,然后是setText方法。setText只有一行代码:super.setText(text.trim())