复选框变化值的两倍

复选框变化值的两倍

本文介绍了复选框变化值的两倍的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Android 的ListView 的项目有一个复选框。

I have an Android ListView whose items have a checkbox.

该复选框被默认选中。一旦选中应当从列表中删除。

The checkbox is checked by default. Once unchecked it should be removed from the list.

问题是, onCheckedChanged 被解雇两次:当我点击复选框取消选中它(与器isChecked )后,我删除的项目(以器isChecked

The problem is that onCheckedChanged is being fired twice: when I tap the checkbox to uncheck it (with isChecked false) and after I remove the item (with isChecked true).

这是我的ArrayAdapter相关code:

This is the relevant code of my ArrayAdapter:

public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    if (convertView == null) {
        convertView = mInflater.inflate(R.layout.item, parent, false);
        holder = new ViewHolder();
        holder.check = (CheckBox) convertView.findViewById(R.id.check);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    final Object item = this.getItem(position);
    holder.check.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (!isChecked) {
                remove(item); // This somehow calls onCheckedChanged again
            }
        }
    });
    return convertView;
}

我是什么做错了吗?

What am I doing wrong?

推荐答案

我遇到同样的问题,这似乎是一个Android的bug这两次执行onCheckChanged方法。

I encountered the same problem, it seems to be an Android bug this twice execution of onCheckChanged method.

我的解决办法:执行 onClickListener ,而不是 onCheckedChangedListener 的。

My solution: implement onClickListener, instead of onCheckedChangedListener.

事情是这样的:

private final class CheckUpdateListener implements OnClickListener {

    private Group parent;
    private boolean isChecked;

    private CheckUpdateListener(Group parent) {

        this.parent = parent;

    }

    @Override
    public void onClick(View box) {
        this.isChecked = !parent.isChecked();

        parent.setChecked(isChecked);

        notifyDataSetChanged();

    }

}

这篇关于复选框变化值的两倍的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-23 12:55