【问题标题】:Checkboxes not staying checked custom adapter复选框未选中自定义适配器
【发布时间】:2014-03-20 01:12:08
【问题描述】:

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

@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 + "");
            }
        });

【问题讨论】:

标签: android checkbox android-listview android-adapter


【解决方案1】:

正如 Raghunandan 所建议的,发生这种情况是因为 ListView 会回收视图,因此 convertView 大多数时候可能不为空。试试这个:

@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);
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    • 2015-01-25
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多