我试图根据用户在对话框中的输入使用唯一字符串填充操作栏微调器,例如,用户输入一个字符串,如果微调器中没有它,它应该将自己添加到那里。这样的实现可能吗?我尝试使用 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());
}
});
最佳答案
我建议在添加到类别之前检查它是否已经在使用 ArrayList.contains 之前添加过: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#contains(java.lang.Object)
要考虑的另一件事是区分大小写,也许您可以在 检查它是否已存在于数组列表中并仅在不存在时才添加小写。
关于java - 用独特的字符串填充微调器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18599592/