EditTextPreference.setText(value) not updating as expected

≡放荡痞女 提交于 2019-12-06 00:08:44
Michael Marvick

Finally found a solution by doing the following:

  • I used a SharedPreferences.OnSharedPreferenceChangeListener instead of a Preference.OnPreferenceChangeListener. The Preference.OnPreferenceChangeListener looks for when the user changes a preference through the settings menu, and behaves before the change is committed to the preference data. The SharedPreferences.OnSharedPreferenceChangeListener listens for changes to the actual preference data, not changes in the GUI, so it happens a little later. I noticed that in my first attempt, I could run setText() immediately followed by getText() on my EditTextPreference object, and the getText() value wouldn't match what I had just set the setText() value to. I'm not sure why this happens, but waiting for the changes to actually commit before trying to run setText() led to the correct response. Maybe it was a timing issue?

  • I run setPreferenceScreen(null) and addPreferencesFromResource(R.xml.settings) after updating the value in the EditTextPreference. If I didn't do this, sometimes when the user would click on the EditTextPreference again, the value in the field would appear blank even though the value in the settings file wasn't. This forces the settings page to, more or less, refresh itself.

The working code is below:

public class SettingsActivity extends PreferenceActivity {

    private String oldCatName;
    private EditTextPreference catName;
    private SharedPreferences.OnSharedPreferenceChangeListener listener;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
        createListener();
        catName = (EditTextPreference) findPreference("cat_name");
        oldCatName = catName.getText();
    }

    private void createListener() {
        listener = new SharedPreferences.OnSharedPreferenceChangeListener() {
            @Override
            public void onSharedPreferenceChanged(
                    SharedPreferences sharedPreferences, String key) {
                String value = sharedPreferences.getString("cat_name", "NULL");
                if (value.equals("")) {
                    catName.setText(oldCatName);
                    setPreferenceScreen(null);
                    addPreferencesFromResource(R.xml.settings);
                } else {
                    oldCatName = value;
                }
            }
        };
        PreferenceManager.getDefaultSharedPreferences(getApplicationContext())
            .registerOnSharedPreferenceChangeListener(listener);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!