我有一个带有一些预填充数据的自定义数组适配器,更多数据将从用户输入中添加到它。问题是重复值仍然添加到数组适配器中。这是我的代码:
String s;//holds data from user input
for(int i=0 ; i<my_adapter.getCount() ; i++){
MyCollection itemObject=my_adapter.getItem(i);
//MyCollection is an object from the collection class
String c=itemObject.toString();
if(c.matches(s)){
//do not add s to array adapter
}else{
//add s to arrayadapter
my_arrayvalues.add(new MyCollection(s));
my_adapter.notifyDataSetChanged();
}
运行上面的代码,即使值不匹配,也不会对适配器产生任何影响..如果我只是运行项目而不包括上面的代码 添加了重复值。我该如何更正此问题?
按照我按照建议完成的答案进行操作后,仍然添加了重复项: 更新后的代码
hs = new HashSet();
my_arrayvalues.add(new MyCollections(s));
hs.addAll(my_arrayvalues);
my_arrayvalues.clear();
my_arrayvalues.addAll(hs);
my_adapter.notifyDataSetChanged();
最佳答案
您可以使用不允许重复的集合。由于您已经实现了自定义适配器,因此您可以避免将数据集传递给 ArrayAdapter 的 super 构造函数,并覆盖您需要的方法。
例如你可以使用一个
LinkedHashSet
并且 getCount 方法应该返回 LinkedHashSet
的 this。此外,您的类可以扩展 BaseAdapter
而不是 ArrayAdapter
关于java - 如何确保 arrayadapter 不接受重复值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21407605/