SharedPreferences.Editor 在初始提交后未更新
我在这里有点困惑。我正在尝试更改 EditTextPreference 的值,但它没有在视图中更新。 (这是在 PreferenceActivity 中)
这是我的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.modify_instrument_preferences);
// Set default values
SharedPreferences customSharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = customSharedPreference.edit();
modifying = getObjectWithName(); //Some object with a name;
editor.putString("namePref", modifying.getName());
editor.commit();
android.util.Log.d("TEST", "written: "+customSharedPreference.getString("namePref",""));
}
我的 printlns 打印出有效信息,并且 commit() 返回 true,但是单击 EditTextPreference 时,它会显示旧值。如果我旋转屏幕,导致 onCreate 再次运行,则 EditTextPreference 具有正确的值。
太令人困惑了。为什么此更改没有在 UI 中更新?
编辑:
我不确定为什么上面的方法不起作用,但我设法通过执行以下操作来更改它:
EditTextPreference namePref = (EditTextPreference) findPreference("namePref");
namePref.setText("the text");
每次都会更新视图。
I'ma a bit confused here. I'm trying to change the value of an EditTextPreference, but it is not updated in the view. (This is in a PreferenceActivity)
Here is my code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.modify_instrument_preferences);
// Set default values
SharedPreferences customSharedPreference = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = customSharedPreference.edit();
modifying = getObjectWithName(); //Some object with a name;
editor.putString("namePref", modifying.getName());
editor.commit();
android.util.Log.d("TEST", "written: "+customSharedPreference.getString("namePref",""));
}
My printlns print out valid information, and the commit() returns true, but on clicking the EditTextPreference, it displays the old value. If I rotate the screen, causing the onCreate to get run again, the EditTextPreference has the right value.
So perplexing. Why isn't this change being updated in the UI?
Edit:
I'm not sure why the above isn't working, but I managed to change it just by doing:
EditTextPreference namePref = (EditTextPreference) findPreference("namePref");
namePref.setText("the text");
That updated the view everytime.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尽管我知道 PreferenceActivities 有一些构造可以自行跟踪此信息,但似乎没有很好的记录。我发现向首选项添加
onPreferenceChangeListener
将允许您在首选项更改后立即进行这些编辑。Although I know there are some constructs in place for PreferenceActivities to keep track of this info themselves, it doesn't seem to be well documented. I have found that adding an
onPreferenceChangeListener
to the preference will allow you to make those edits as soon as the preference is changed.