使用自定义适配器获取选中的项

时间:2015-08-21 17:53:00

标签: java android listview

我有自定义适配器的listview。此列表视图的每个元素都有复选框。标准函数.getCheckedItemPositions()不起作用。

的onCreate:

=Average(Abs(B1:B15-A1:A15))

我的适配器:

  final String[] words = new String[] {
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13"
        };


        MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, words);
        listView.setAdapter(adapter);

在这里,我尝试获取检查项目:

public class MySimpleArrayAdapter extends ArrayAdapter<String> {
    private final Context context;
    private final String[] values;
    DataBaseHelper myDbHelper;
    int id = 1;


    public MySimpleArrayAdapter(Context context, String[] values) {
        super(context, R.layout.listitem, values);
        this.context = context;
        this.values = values;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View rowView = inflater.inflate(R.layout.listitem, parent, false);
        CheckBox checkBox = (CheckBox)rowView.findViewById(R.id.checkBox);
        TextView newwordview = (TextView)rowView.findViewById(R.id.newwordview);


        newwordview.setText("lalala");

            return rowView;
    }
}

在debug中,sparseBooleanArray总是有0个项目。 我该怎么办?

1 个答案:

答案 0 :(得分:1)

您可能应该使Adapter一个可以保留其已检查状态的对象列表,而不是字符串。

public class Item
{
    public String title;
    public boolean checked;
}

然后:

public class MySimpleArrayAdapter extends ArrayAdapter<Item>
{
    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        View rowView = inflater.inflate(R.layout.listitem, parent, false);
        CheckBox checkBox = (CheckBox)rowView.findViewById(R.id.checkBox);
        TextView newwordview = (TextView)rowView.findViewById(R.id.newwordview);

        Item item = getItem(position);
        newwordview.setText(item.title);
        checkBox.setChecked(item.checked);


        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            @Override
            public void onCheckedChanged(CompoundButton view, boolean isChecked)
            {
                Item item = getItem(position);
                item.checked = isChecked;
            }
        });

        return rowView;
    }
}

另请注意:出于性能原因,您应该在出现时重新使用convertView。我建议查看视图持有者模式: How can I make my ArrayAdapter follow the ViewHolder pattern?