我将选中的项目添加到arraylist中,但是当我单击某个项目时总是将其追加。另外,当我取消选中它时,它也会追加到arraylist中。这是代码:
List<String> ingList = new ArrayList<String>();
List<String> onhandIngList = new ArrayList<String>();
ingList.add("one");
ingList.add("two");
intList.add("three");
//displays the arraylist using arrayadapter
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_multiple_choice, ingList);
if(ingList.size() != 0) {
listView.setAdapter (arrayAdapter);
}else{
Toast.makeText (Ingredients.this, "No data", Toast.LENGTH_SHORT).show ();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int index, long l) {
Object clickItemObj = adapterView.getAdapter().getItem(index);
onhandList.add(( String ) clickItemObj);
}
});
我希望输出将是选中项目的值。但是没有重复的输出。
答案 0 :(得分:0)
也许您应该尝试类似的操作(在onItemClick()内部):
SparseBooleanArray checked = listView.getCheckedItemPositions();
if(checked.get(index)){
onhandlist.add(...)
}
else{
onhandList.remove(...)
}