共享首选项的键值仅被更改一次

时间:2017-06-01 15:48:24

标签: android sharedpreferences android-theme

我正在尝试在我的应用中添加更改主题的功能。单击按钮后显示带有单项选项(单选按钮)的AlertDialog。

这是AlertDialog:

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.widget.Toast;
public class ThemeDialog extends DialogFragment {
    SharedPreferences preferences;
    SharedPreferences.Editor editor;
    int radioButton;
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    preferences = getActivity().getPreferences(0);
    editor = preferences.edit();
    editor.apply();

    if (preferences.getBoolean("has_theme_changed", false)) {
        radioButton = 1;
        Toast.makeText(getActivity(), "true", Toast.LENGTH_SHORT).show();
    } else { radioButton = 0; Toast.makeText(getActivity(), "false", Toast.LENGTH_SHORT).show();}

    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle(R.string.theme_dialog_title)
            .setSingleChoiceItems(R.array.choose_a_theme, radioButton, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    switch (which) {
                        case 0:
                            editor.putBoolean("has_theme_changed", false);
                            editor.apply();
                            dismiss();
                        case 1:
                            editor.putBoolean("has_theme_changed", true);
                            editor.apply();
                            dismiss();
                    }
                }
            });

    return builder.create();
}
}

首先,我想要的是当用户选中任一单选按钮时,下次应默认选中它。

其次,根据SharedPreference对象中保存的布尔值,主题应在MainActivity中更改。

问题:默认值为'false',因此主题为'light',并选中'Light Theme'单选按钮。当我尝试将其改为“黑暗”时,它的工作就像一个魅力,但它后来停止工作。谁能指出什么是错的?如果您认为,请分享您的观点,有更好的方法在运行时更改应用程序的主题。提前谢谢!

3 个答案:

答案 0 :(得分:0)

尝试更改此

preferences = getActivity().getPreferences(0);

这个

preferences = getActivity().getSharedPreferences( getString(R.string.preference_file_key), Context.MODE_PRIVATE);

请记住在strings.xml

中设置字符串preference_file_key

答案 1 :(得分:0)

这是因为你忘了打开开关盒。

foo (bar))

顺便说一下,你不需要editor.apply():

switch (which) {
    case 0:
        editor.putBoolean("has_theme_changed", false);
        editor.apply();
        dismiss();
        break;
    case 1:
        editor.putBoolean("has_theme_changed", true);
        editor.apply();
        dismiss();
        break;
}

答案 2 :(得分:0)

我看到更简单的方法,删除那个糟糕的开关,只需将以下内容放在你的onClick()中:

editor.putBoolean("has_theme_changed", which == 1).apply();
dismiss();

不需要开关也不需要2次调用dismiss()

我想知道你是否能在这种情况下做到这一点:

editor.putBoolean("has_theme_changed", Boolean.valueOf(which)).apply();
dismiss();

**编辑**

第二个例子似乎不正确,因为doc说Boolean.valueOf只接受字符串或布尔值