2012-10-10 59 views
0

我有一個延伸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

在適配器只需創建方法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(); 
+0

我認爲,在我的適配器有一個方法找到檢查項目ID並刪除它。類似於public long getItemId(int position)返回位置; }但我調用它堆疊。我是一個新的。 – user1706819

+0

你是否正在從'ListActivity'擴展你的活動? – Jin35

+0

public class ChildActivity extends Activity { – user1706819