在setOnCheckedChangeListener中为BaseAdapter更新列表中的数据

时间:2014-02-13 13:38:03

标签: android listview oncheckedchanged

我有以下代码:

    public class MyListAdapter extends BaseAdapter {

    private final List<MyClass> mItems = new ArrayList<MyClass>();
...

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    final MyClass myItem = mItems.get(position);
    if (rowView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.my_item, null);
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.cbView = (CheckBox) rowView.findViewById(R.id.cbCheckBox);
        viewHolder.cbView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                myItem.setState(isChecked);
            }
        });
        rowView.setTag(viewHolder);
    }

我对听众非常不舒服。它指的是当convertView为null时创建的myItem。如果我从列表中删除该项目(位置更改)该怎么办?或者如果我在它前面添加一些项目?我的代码会因“null异常”而失败吗?或者执行不正确? 我应该如何构建它?

1 个答案:

答案 0 :(得分:0)

如果convertView为null,则只需创建视图对象... 现在,如果从列表中间删除视图,则从底部查看提升并替换已删除视图的空间。并且当视图抬起时,viewHolder对象将创建新的视图并保持更新的viewHolder对象。

@Override
    public View getView(int position, View convertView, ViewGroup parent) {
    View rowView = convertView;
    final MyClass myItem = mItems.get(position);
    if (rowView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        rowView = inflater.inflate(R.layout.my_item, null);
       }
        ViewHolder viewHolder = new ViewHolder();
        viewHolder.cbView = (CheckBox) rowView.findViewById(R.id.cbCheckBox);
        viewHolder.cbView.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                myItem.setState(isChecked);
            }
        });
        rowView.setTag(viewHolder);
    }