android - 保留 AlertDialog 选中的选项

标签 android arraylist sharedpreferences android-alertdialog

我已经为此苦苦挣扎了两个多星期。关于 sharedpreferenes 和其他“hacks”的所有 SO 问题,以坚持多项选择警报对话框。但不幸的是我仍然无法让它工作。

有人可以向我解释如何让这个东西工作吗?我的多项选择警报对话框有效。但我仍然无法保存所选项目..

我的代码:

    public class TimelineSettings extends DialogFragment {
    Context context;
    final ArrayList selected_categories = new ArrayList();
    final String[]items = {"Fourniture","Nourriture","Voyages","Habillement","Médias","Autres"};
    TinyDB tinydb = new TinyDB(context);
    private SharedPreferences sharedPreference;
    private SharedPreferences.Editor sharedPrefEditor;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        // Set the dialog title
        builder.setTitle("Choisissez vos paramètres")
                .setMultiChoiceItems(items, null,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int indexselected,
                                                boolean isChecked) {
                                if (isChecked) {
                                    // If the user checked the item, add it to the selected items
                                    selected_categories.add(indexselected);
                                } else if (selected_categories.contains(indexselected)) {
                                    // Else, if the item is already in the array, remove it
                                    selected_categories.remove(Integer.valueOf(indexselected));
                                }
                            }
                        })
                        // Set the action buttons
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                    tinydb.putList("selected",selected_categories);
                    }
                })
                .setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                    }
                });
        return builder.create();
    }
}

感谢您的帮助。

PS:我遇到了这个answer ,如果你能向我解释如何使这项工作,那就太好了。

最佳答案

小心,因为你正在节省 Integers在首选项中,然后您正在转换 ArrayListIntegersArrayListStrings .这可能会导致 Exception .使用 ArrayListsStrings到处都是。

在显示 DialogFragment 之前,您只漏掉了一部分, 你必须阅读你保存的选择并在你的 DialogFragment 中检查它们.

有最简单的方法可以做您想做的事,但让我们采用这种方法:

如您所见,setMultiChoiceItems()方法接收 String[]作为您的 DialogFragment 的项目和一个 boolean []定义它们是否被选中。我们将使用这个数组来保存我们的选择。该数组的长度必须与 items 数组的长度相同,并且初始设置为 false。

第一次启动 DialogFragment , 没有项目被检查。第二次,当您已经检查了项目时,您将从 TinyDB 中读取这些选择并使用 for 语句填充 bool 数组。然后你将它提供给 DialogFragment build 者。

已保存的项目将在 DialogFragment 上显示为选中状态,如你所愿。

这里是完整的更改和工作代码:

    public class TimelineSettings extends DialogFragment {
    ArrayList<String> selected_categories = new ArrayList<String>();
    final String[]items = {"Fourniture","Nourriture","Voyages","Habillement","Médias","Autres"};
    boolean[] itemsChecked = {false, false, false, false, false, false};
    TinyDB tinydb;
    private SharedPreferences sharedPreference;
    private SharedPreferences.Editor sharedPrefEditor;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        tinydb = new TinyDB(getActivity());
        selected_categories = tinydb.getList("selected");

        for(int i=0;i<itemsChecked.length;i++){
            if(selected_categories.contains((String)String.valueOf(i)))
                    itemsChecked[i]=true;
        }

        // Set the dialog title
        builder.setTitle("Choisissez vos paramètres")
                .setMultiChoiceItems(items, itemsChecked,
                        new DialogInterface.OnMultiChoiceClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int indexselected,
                                                boolean isChecked) {
                                if (isChecked) {
                                    // If the user checked the item, add it to the selected items
                                    if(!selected_categories.contains((String)String.valueOf(indexselected))){
                                        selected_categories.add(String.valueOf(indexselected));
                                        itemsChecked[indexselected]=true;
                                    }
                                } else if (selected_categories.contains((String)String.valueOf(indexselected))) {
                                    // Else, if the item is already in the array, remove it
                                    selected_categories.remove((String)String.valueOf(indexselected));
                                    itemsChecked[indexselected]=false;
                                }
                            }
                        })
                        // Set the action buttons
                .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                        tinydb.putList("selected",selected_categories);
                    }
                })
                .setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int id) {
                    }
                });
        return builder.create();
    }
}

关于android - 保留 AlertDialog 选中的选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26482096/

相关文章:

android - 线性渐变和位图着色器运行不佳

java - 在 Java 中将对象作为列表输入到数组中

java - 尝试实现 SharedPreferences 时遇到困难

android - 反序列化 json 对象失败

android - android中的内部存储

android - KitKat 及以下版本的 VectorDrawableCompat Resources$NotFoundException

java - 用图像(.png)填充 ShapeRenderer 矩形?

java arrayList循环性能

java - java中如何创建可以存储多种数据类型对象的arraylist类

java - 我使用 shareDpreferences 将字符串保存在 textView 中,关闭应用程序并再次打开后,它不起作用