如果我选中列表视图顶部的任何复选框,则会检查列表下方的复选框

时间:2014-12-16 13:42:16

标签: android checkbox

发生了什么: Listview我能够勾选复选框,当我滚动列表中的列表元素时,列表中的复选框被选中

我该如何解决这个问题!


{更新代码}

AdptSearchFilterCategories.java

 public class AdptSearchFilterCategories extends ArrayAdapter<ModelFilterCategories> {

    private Context context;
    List<ModelFilterCategories> mdlLst;


    public AdptSearchFilterCategories(Activity context, List<ModelFilterCategories> mdlLst) {
        super(context, R.layout.adpt_searchfilter_category, mdlLst);
        this.context = context;
        this.mdlLst = mdlLst;
    }


    static class ViewHolder {
        protected CheckBox chkBxCatId;
    }

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


        ViewHolder viewHolder = null;
        if (convertView == null) {
            LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
            convertView = mInflater.inflate(R.layout.adpt_searchfilter_category, null);

            viewHolder = new ViewHolder();
            viewHolder.chkBxCatId = (CheckBox) convertView.findViewById(R.id.chkBxCatId);
            viewHolder.chkBxCatId.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                            int getPosition = (Integer) buttonView.getTag();  // Here we get the position that we have set for the checkbox using setTag.
                            mdlLst.get(getPosition).setCheckboxState(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
                        }
                    });
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }

        viewHolder.chkBxCatId.setTag(position); // This line is important.
        viewHolder.chkBxCatId.setText(mdlLst.get(position).getCategoryName());

        return convertView;
    }

}

1 个答案:

答案 0 :(得分:0)

复选框的状态已复制到其他视图,因为适配器正在重用convertview。

  1. 我建议在isChecked对象中添加Model变量。
  2. 在&#34;获取视图&#34;方法,你应该使用这个:

    viewHolder.checkbox.setChecked(list.get(position).isChecked);
    
  3. 不要使用setOnCheckedChangeListener,因为:

    viewHolder.checkbox.setChecked(list.get(position).isChecked);
    

    将调用onCheckedChanged方法。

  4. viewHolder.checkbox上实现OnClickListener,当您获得click事件时,只需切换布尔状态(使用Model.isChecked = !Model.isChecked)然后notifyDataSetChanged