元素被添加到arraylist检查复选框,但不取消选中它。 取消选中复选框,我必须从arraylist中删除元素。 我写了下面的代码,让我知道我错了。我必须删除从arraylist元素取消选中复选框
public class CustomAdapter extends BaseAdapter{
NameModel model;
public static ArrayList<NameModel> nameArray;
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater mInflater = (LayoutInflater)context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.item_list, null);
name = (TextView)convertView.findViewById(R.id.name);
cb = (CheckBox)convertView.findViewById(R.id.checkBox1);
cb.setTag(position);
nameArray = new ArrayList<NameModel>();
cb.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
int position = (Integer)view.getTag();
CheckBox checkbox = (CheckBox)view;
model = new NameModel(NameList.get(position).getName());
model.setCheckedStatus(checkbox.isChecked());
model.setName(NameList.get(position).getName());
if(checkbox.isChecked()){
CustomAdapter.nameArray.add(model);
Toast.makeText(context, "item checked ", Toast.LENGTH_SHORT).show();
}else{
CustomAdapter.nameArray.remove(model);
Toast.makeText(context, "item unchecked ", Toast.LENGTH_SHORT).show();
}
}
});
}
return convertView;
}
我宣布ArrayList中为静态,因为它不是在getView方法访问。
执行时,按预期方式打印两个吐司,但不取消选中复选框时删除该元素。
对上述问题的任何帮助将不胜感激。 在此先感谢。
如何从列表中删除不存在的项目? –
我有一个复选框的自定义列表。第一个用户将通过选中该复选框从列表中选择任何元素,并将该元素添加到ArrayList中。但是通过取消选中复选框来取消选择该元素时,该元素应该从ArrayList中移除。 – user3098795
NameModel有一个equals和hash代码实现? – StackFlowed