在 Android 4 中,我有一个偏好值,我想以标准形式 E2C56DB5-DFFB-48D2-B060-D0F5A71096E0 出现。但是用户可以输入不带破折号的值。我想允许用户使用空格或破折号的任意组合输入它,并且只需让我的代码对其进行规范化。
我正在使用下面的代码,我看到了日志行,但它什么也没做。我猜这是因为 Android 打开了另一个编辑器对象,它覆盖了我的更改。有没有其他方法可以做到这一点?
public class UuidFragment extends PreferenceFragment {
...
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
this.getPreferenceScreen().findPreference("pref_uuid").setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
if (newValue.toString().length() != 0) {
String normalizedUuid=normalizeUuid(newValue.toString());
// TODO: this code runs but does nothing, I think because after committing the change, there is a higher level editor that commits the old value
// thereby undoing this change
if (!normalizedUuid.equals(newValue.toString())) {
Log.d(TAG, "Adjusting uuid from "+newValue.toString()+" to "+normalizedUuid);
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(UuidFragment.this.getActivity());
SharedPreferences.Editor editor = settings.edit();
editor.putString(preference.getKey(), normalizedUuid);
editor.commit();
}
return true;
}
}
});
}
}