我的Box适配器扩展了BaseAdapter
public class BoxAdapter extends BaseAdapter {
Context ctx;
LayoutInflater lInflater;
ArrayList<Product> objects;
CheckBox cbBuy;
BoxAdapter(Context context, ArrayList<Product> products) {
ctx = context;
objects = products;
lInflater = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return objects.size();
}
@Override
public Object getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// используем созданные, но не используемые view
View view = convertView;
if (view == null) {
view = lInflater.inflate(R.layout.childitem, parent, false);
}
Product p = getProduct(position);
((TextView) view.findViewById(R.id.tvDescr)).setText(p.name);
((TextView) view.findViewById(R.id.tvPrice)).setText(p.price + "");
((ImageView) view.findViewById(R.id.ivImage)).setImageResource(p.image);
cbBuy = (CheckBox) view.findViewById(R.id.cbBox);
cbBuy.setOnCheckedChangeListener(myCheckChangList);
cbBuy.setTag(position);
cbBuy.setChecked(p.box);
return view;
}
Product getProduct(int position) {
return ((Product) getItem(position));
}
ArrayList<Product> getBox() {
ArrayList<Product> box = new ArrayList<Product>();
for (Product p : objects) {
// если в корзине
if (p.box)
box.add(p);
}
return box;
}
OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
getProduct((Integer) buttonView.getTag()).box = isChecked;
}
};
}
现在在MainActivity中我必须找出选中的复选框并将其删除。
我该怎么办?调用getItemId位置的方法和方法。提前谢谢。
case R.id.delete:
if (boxAdapter.cbBuy.isChecked()) {
products.remove( checked position id );
}
答案 0 :(得分:0)
只需在适配器中创建方法getBoxProducts
:
public void removeBoxProducts()
{
List<Product> trash = new ArrayList<Product>();
for (Product product:objects)
{
if (product.box)
{
trash.add(product);
}
}
for (Product product:trash)
{
objects.remove(product);
}
}
要访问此方法,请使用以下命令:
ListView list = (ListView) findViewByIf(R.id.list_view_id);
BoxAdapter adapter = (BoxAdapter)list.getAdapter();
adapter.removeBoxProducts();
adapter.notifyDataSetChanged();