0
在Android 4中,我有一个首选值,我想以标准格式E2C56DB5-DFFB-48D2-B060-D0F5A71096E0出现。但是用户可以输入没有破折号的值。我想允许用户输入任何空格或破折号的组合,并简单地让我的代码正常化它。是否可以在更改时规范化Android偏好值?
我使用下面的代码,我看到日志行,但它什么都没做。我猜测这是因为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;
}
}
});
}
}