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

时间:2017-10-09 22:12:12

标签: android android-fragments android-preferences preferenceactivity

我正在开发一款具有一些设置的Android应用。它仍然是一个草稿,但我遇到了一个我不能成功解决的问题:我创建了一个示例设置活动(使用Android开发人员指南建议的PreferenceFragment),我添加了一个"恢复默认设置"按钮。但是,此按钮仅部分有效 - 它仅恢复编辑文本首选项,但不恢复其余部分。我的意图是,当我按下按钮时,所有首选项都应恢复为preferences.xml文件中显示的值。

这里是代码:

主要活动

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);
    }
}

设置活动

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>

1 个答案:

答案 0 :(得分:1)

我有一个类似的问题-我的EditTextPreferences更改了,但是当我单击它们时,它显示了旧值。当我关闭偏好设置屏幕并返回时,一切都很好。

我解决了这个问题,并验证了其他首选项的工作原理相同,但是您看到的方式不同。当您重新打开首选项屏幕时,将F.E. CheckBoxPreference还原为默认值。但单击“恢复默认设置”后,该按钮将无法正常工作,因为它不会刷新代码中的首选项屏幕。

我只是将其修改为:

 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
}

我不知道这是最好的解决方案,但是它可以工作