1

我试图根据对话框中的用户输入来填充具有唯一字符串的操作栏微调器,例如,用户输入一个字符串,如果它不在微调器中,它应该在那里添加自己。这样的实现可能吗?我尝试使用 ArrayList 类,但当然存在重复项,我应该使用 hashset 吗?谢谢

// array of sample strings to popluate dropdown list
ArrayList<String> categories = new ArrayList<String>();

// create an array adapter to popluate dropdown list
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getBaseContext(),
            android.R.layout.simple_spinner_dropdown_item, categories);

 //thats the alert dialog through which user enters strings
 AlertDialog.Builder alert = new AlertDialog.Builder(this);

        alert.setTitle("New category");
        alert.setMessage("Please enter a new category ");

        // Set an EditText view to get user input
        final EditText input = new EditText(this);
        alert.setView(input);

        alert.setPositiveButton("Ok",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog,
                            int whichButton) {
                        Editable value = input.getText();
                        // Do something with value!

                        categories.add(value.toString());

                    }
                });
4

1 回答 1

3

我建议在添加到您之前检查它是否已经添加或未使用 ArrayList.contains 的类别之前:http: //docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#包含(java.lang.Object)

要考虑的另一件事是区分大小写,也许您可​​以在检查它是否已存在于数组列表中之前转换为小写,如果不存在则仅添加。

于 2013-09-03T19:08:31.287 回答