我在处理ListView
的重复方面遇到问题。正如您在屏幕截图上所看到的,我有一个spinner
,其中包含所有需要的项目。当用户单击该特定项目时,它将添加到我的ListView
上。但是问题是数据被复制了。
这是图片:
场景: 假装这是列表项
A
B
C
D
如果我单击“ A”。它将添加到我的ListView
上对吗?然后点击“ B”。因此,ListView
上的数据是:A和B。如果再次单击“ A”,它将在ListView
上添加当前项。我需要限制当前正在发生的重复。
这是我点击Spinner
public void addViolationListenerOnSpinnerItemSelection() {
spinner_violation.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent2, View view, int position2, long id) {
if (position2 != 0) {
vio_val = String.valueOf(spinner_violation.getSelectedItem());
adapter = new ViolationAdapter(getContext(), generateData());
lv_inspector_violation.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
这是generateData()
private ArrayList<InspectorViolationItem> generateData() {
items.add(new InspectorViolationItem(emp_val, vio_val));
HashSet<InspectorViolationItem> hs = new HashSet<>();
hs.addAll(items);
items.clear();
items.addAll(hs);
return items;
}
InspectorViolationItem
只是一个Getters
和Setters
,所以我认为不需要发布代码。
最后,这是我使用的适配器:
public class ViolationAdapter extends ArrayAdapter<InspectorViolationItem> {
Context c;
private ArrayList<InspectorViolationItem> itemsArrayList;
public ViolationAdapter( Context context, ArrayList<InspectorViolationItem> itemsArrayList) {
super(context, R.layout.item_violation, itemsArrayList);
this.c = context;
this.itemsArrayList = itemsArrayList;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = inflater.inflate(R.layout.item_violation, parent, false);
// 3. Get the two text view from the rowView
TextView labelView = (TextView) rowView.findViewById(R.id.txt_violation_employee);
TextView valueView = (TextView) rowView.findViewById(R.id.txt_violation_violation);
// 4. Set the text for textView
labelView.setText(itemsArrayList.get(position).getEmployee());
valueView.setText(itemsArrayList.get(position).getViolation());
// 5. retrn rowView
return rowView;
}
}
答案 0 :(得分:0)
我通过将所选项目放在ArrayList<>
上
并进行如下验证:
if (position2 != 0) {
vio_val = String.valueOf(spinner_violation.getSelectedItem());
if (!violationHolder.contains(vio_val)) {
adapter = new ViolationAdapter(getContext(), generateData());
violationHolder.add(vio_val);
lv_inspector_violation.setAdapter(adapter);
adapter.notifyDataSetChanged();
} else {
Toast toast = Toast.makeText(getContext(), "Duplicate Violation.", Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
感谢您的帮助