选择和删除listview中的项目

时间:2016-04-12 10:58:14

标签: android listview

我尝试使用用户应该突出显示/检查的项目制作列表视图,然后按下按钮“删除”#39;。它将从列表中删除这些项目。

问题是我似乎无法让它工作,我的SparseBooleanArray似乎正确地返回所选项目。但我尝试用新颜色突出显示背景。似乎工作,但当我scrool它将选择列表中的随机项目,当我再次尝试再次扫描它所有随机的项目被检查/选择。

    m_orders = new ArrayList<Products>();
    this.m_adapter = new OrderAdapter(this, R.layout.orderrow, m_orders);
    lv = (ListView)findViewById(R.id.listView);
    lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    lv.setItemsCanFocus(false);
    lv.setAdapter(m_adapter);

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            SparseBooleanArray array =  lv.getCheckedItemPositions();
            int len = lv.getCount();
            for (int i = 0; i < len; i++){
                if (array.get(i)) {
                    Products item = m_orders.get(i);
                    view.setBackgroundColor(Color.BLUE);
                }else{
                    view.setBackgroundColor(Color.WHITE);
                }
            }
        }
    });

OrderAdapter

private class OrderAdapter extends ArrayAdapter<Products> {

    private ArrayList<Products> items;

    public OrderAdapter(Context context, int textViewResourceId, ArrayList<Products> items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.orderrow, null);
        }
        Products o = items.get(position);
        if (o != null) {
            ImageView iv = (ImageView) v.findViewById(R.id.icon);
            TextView tt = (TextView) v.findViewById(R.id.toptext);
            TextView bt = (TextView) v.findViewById(R.id.bottomtext);
            LinearLayout or = (LinearLayout) v.findViewById(R.id.orderrow);

            if (tt != null) {
                tt.setText(""+o.get_name());
            }
            if(bt != null){
                bt.setText(""+ new BigDecimal(o.get_price()).movePointLeft(2));
                //bt.setText(""+o.get_price());
            }
            if(iv != null){
                if(o.get_orderStatus()){
                    iv.setImageResource(R.drawable.checkmark);
                }else{
                    // dont do anything as the item has not been paid yet
                }
            }
        }
        return v;
    }
}

1 个答案:

答案 0 :(得分:0)

删除适配器的getView方法中的条件。

if (v == null)