android 恢复应用程序的默认首选项

android restore application's default preferences

我正在开发一个 android 应用程序,它有一些设置。它仍然是一个草稿,但我遇到了一个我没有成功解决的问题:我创建了一个示例设置 activity(使用 android 开发人员指南建议的 PreferenceFragment),并且我添加了一个 "restore default settings" 按钮。但是,此按钮仅部分起作用 - 它仅恢复编辑文本首选项,而不恢复其余部分。我的意图是,当我按下按钮时,所有首选项都应恢复为 preferences.xml 文件中出现的值。

代码如下:

主要Activity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
    }

    public void applyCoF(View view) {
    }

    public void changeSettings(View view) {
        Intent settingsIntent = new Intent(this, SettingsActivity.class);
        startActivity(settingsIntent);
    }
}

设置Activity

public class SettingsActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsFragment()).commit();

    }


    public static class SettingsFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener {

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.preferences);
            getPreferenceScreen().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

            Preference button = findPreference(getString(R.string.restoreDefaultSettingsButton));
            button.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
                @Override
                public boolean onPreferenceClick(Preference preference) {
                    //code for what you want it to do
                    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case DialogInterface.BUTTON_POSITIVE:
                                    //Yes button clicked
                                    restoreDefaultSettings();
                                    break;

                                case DialogInterface.BUTTON_NEGATIVE:
                                    //No button clicked
                                    break;
                            }
                        }
                    };

                    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setTitle(R.string.restoreDefaultSettingsDialogTitle);
                    builder.setMessage(R.string.restoreDefaultSettingsDialogText).
                            setPositiveButton("Yes", dialogClickListener).
                            setNegativeButton("No", dialogClickListener).
                            show();
                    return true;
                }
            });
        }

        private void restoreDefaultSettings() {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
            SharedPreferences.Editor editor = preferences.edit();
            editor.clear();
            editor.apply();
            PreferenceManager.setDefaultValues(getActivity(), R.xml.preferences, true);
        }

        @Override
        public void onResume() {
            super.onResume();
            for (int i = 0; i < getPreferenceScreen().getPreferenceCount(); ++i) {
                Preference preference = getPreferenceScreen().getPreference(i);
                if (preference instanceof PreferenceGroup) {
                    PreferenceGroup preferenceGroup = (PreferenceGroup) preference;
                    for (int j = 0; j < preferenceGroup.getPreferenceCount(); ++j) {
                        Preference singlePref = preferenceGroup.getPreference(j);
                        updatePreference(singlePref, singlePref.getKey());
                    }
                } else {
                    updatePreference(preference, preference.getKey());
                }
            }
        }

        @Override
        public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
            updatePreference(findPreference(key), key);
        }

        private void updatePreference(Preference preference, String key) {
            if (preference == null || preference instanceof CheckBoxPreference) {
                return;
            }
            if (preference instanceof ListPreference) {
                ListPreference listPreference = (ListPreference) preference;
                listPreference.setSummary(listPreference.getEntry());
                return;
            }

            SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();
            preference.setSummary(sharedPrefs.getString(key, "Default"));
        }
    }
}

preferences.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">


    <CheckBoxPreference
        android:defaultValue="true"
        android:key="check_box_preference_1"
        android:title="Check box preference"/>
    <EditTextPreference
        android:defaultValue="DEFAULT EDIT TEXT"
        android:key="edit_text_preference_1"
        android:selectAllOnFocus="true"
        android:singleLine="true"
        android:title="Edit text preference"/>
    <ListPreference
        android:defaultValue="DEFAULT LIST"
        android:entries="@array/list_preference_entry_values"
        android:entryValues="@array/list_preference_entries"
        android:key="list_preference_1"
        android:title="List preference"/>

    <Preference android:title="Restore default values"
                android:summary=""
                android:key="@string/restoreDefaultSettingsButton"/>
</PreferenceScreen>

我有一个类似的问题 - 我的 EditTextPreferences 发生了变化,但是当我点击它们时它显示旧值。当我关闭首选项屏幕并返回时,一切都很好。

我解决了这个问题,并验证了其他首选项的工作方式相同,但您看到的方式不同。 F.E。当您重新打开首选项屏幕时,CheckBoxPreference 恢复为默认值。但它在点击 "restore defaults" 后不起作用,因为它不会刷新您代码中的首选项屏幕。

我简单修改为:

 private void restoreDefaultSettings() {
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
    SharedPreferences.Editor editor = preferences.edit();
    editor.clear();
    editor.apply();
    PreferenceManager.setDefaultValues(getActivity(), R.xml.pref, true);
    getPreferenceScreen().removeAll();
    onCreatePreferences(null,null); //or onCreate(null) in your code
}

我不知道这是最好的解决方案,但它确实有效