检查所有复选框时出现问题

时间:2011-01-11 16:10:03

标签: android checkedtextview

我有两个问题。

第一个问题。
我有一个CheckedTextView“全选”项和一个在MutipleChoice适配器中设置的数组项列表。我目前正在尝试通过选择CheckedTextView将数组项的所有复选框的状态设置为true / false。它有效,但有一个错误。这样,当数组的最后一项为真时,“SelectAll”为true将起作用,但如果数组的最后一项为false,则取消选中所有项目。我想要的是即使任何项目的状态为false,当checkedtextview被选为true时,它将被设置为true。

第二个问题。
当所有数组项的状态都为真时,我似乎无法将checkedtextview设置为true。

这可能是我做错了吗?给予的帮助将不胜感激..

这是CheckedTextView“Select All”的方法

private void markAll (Boolean state) {

    for (int i = 0; i < lv.getCount(); i++) {
        lv.setItemChecked(i, state);
    }           
}

这是用于检查数组项状态的编码

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    for(int i = 0; i < lv.getCount(); i++) {
        //if even 1 of the item is false, the checkedtextview will be set to false
        if(lv.isItemChecked(i) == false) {
            ctv.setChecked(false);
        }
        //if all of the item is true, the checkedtextview will be set to true as well
        //the coding should be done in the if-else below, if i'm not wrong
        if(...) {

        }
    }
}

修改
这是调用我的方法的新代码         ctv.setOnClickListener(new View.OnClickListener(){

        public void onClick(View v) {
            // TODO Auto-generated method stub
            ctv.setClickable(true);
            if(ctv.isPressed() && ctv.isChecked() == false) {
                ctv.setChecked(true);
                markAll(true);
            }
            else {
                ctv.setChecked(false);
                markAll(false);
            }
        }
    });

这是checkedtextview的xml代码

    <CheckedTextView
        android:id="@+id/checkedtext"
        android:layout_width="fill_parent"
        android:layout_height="?android:attr/listPreferredItemHeight"
        android:text="Select all"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:gravity="center_vertical"
        android:clickable="true"
        android:checkMark="?android:attr/listChoiceIndicatorMultiple"
        android:paddingLeft="6dip"
        android:paddingRight="6dip"/>

1 个答案:

答案 0 :(得分:0)

尝试这个重写的逻辑:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {

    ctv.setChecked(true); // assume true at first

    // if even 1 of the item is false, the checkedtextview will be set to false
    for(int i = 0; i < lv.getCount(); i++) {
        if(lv.isItemChecked(i) == false) {
            ctv.setChecked(false);
            break; // exit loop if you have found one false
        }
    }
}

如果检查了列表中的所有项目,这将使ctv处于选中状态,否则如果任何项为false,则ctv将处于未选中状态。

控制点击ctv本身时会发生什么:

ctv.setOnClickListener(new View.OnClickListener() {
    public void onClick(View v) {
        if(ctv.isChecked()) {
                markAll(true); // ctv is checked, so make all others checked
        }
        else {
              markAll(false); // ctv is unchecked, so make all others unchecked
        }
    }
});

你不需要在这里检查其他项目的状态 - 如果它只是'(de)全选'按钮那么它应该只将其自己的状态传播到其他项目。

相关问题