复选框未停留检查自定义适配器

时间:2014-02-19 15:28:01

标签: android checkbox android-listview android-adapter

我有一个listview的自定义适配器。列表视图有一个复选框,但当我向下滚动然后向上滚动时,复选框不会保持检查状态。我有一个Model,在模型中有一个'selected'的布尔值。这是我的适配器,谁能告诉我我做错了什么?我已多次尝试,似乎没有任何工作。

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

        View row = convertView;
        if(convertView == null){
            LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            row = inflater.inflate(R.layout.list_item_row_friends, null);

            CheckBox friend_checkbox = (CheckBox)row.findViewById(R.id.friends_checkbox);


            if(data.get(position).selected) {
                friend_checkbox.setChecked(true);
            } else {
                friend_checkbox.setChecked(false);
            }
        }
CheckBox friend_checkbox = (CheckBox)row.findViewById(R.id.friends_checkbox);
        friend_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                data.get(position).setSelected(isChecked);
                Log.d("FriendAdapter", data.get(position).selected + "");
            }
        });

1 个答案:

答案 0 :(得分:1)

正如Raghunandan所建议的那样,这是因为ListView回收了视图,因此convertView在大多数情况下可能不是null。试试这个:

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

    View row = convertView;
    if(convertView == null){
        LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        row = inflater.inflate(R.layout.list_item_row_friends, null);
    }
    CheckBox friend_checkbox = (CheckBox)row.findViewById(R.id.friends_checkbox);
    friend_checkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            data.get(position).setSelected(isChecked);
            Log.d("FriendAdapter", data.get(position).selected + "");
        }
    });
    if(data.get(position).selected) {
        friend_checkbox.setChecked(true);
    } else {
        friend_checkbox.setChecked(false);
    }
}