1

我正在尝试制作类似 gmail 的列表视图。That is, initially, the listview is in single choice mode, but when a checkbok is selected, it becomes multiple choice.

这是我到目前为止所拥有的:

     SimpleCursorAdapter dataSource = new SimpleCursorAdapter(this, R.layout.listitem, cursor,
             new String[]{"_id","a","b","c","d","e","f","g","h"}, 
             new int[] { R.id.checkBox1, R.id.a, R.id.b, R.id.c, R.id.d, R.id.e}
// all of these are a part of my list item custom layout.
             );

    dataSource.setViewBinder(new SimpleCursorAdapter.ViewBinder() {

@Override
public boolean setViewValue(View aView, final Cursor c, int i) {

    String s=c.getString(i);
    String toset="";
    TextView tv = i==0?null: (TextView) aView;
    if (i==0){
        if(chkL==null){
            chkL=new OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton cb1, boolean isChecked) {
                    CheckBox cb=(CheckBox) cb1;
                    chkid[c.getPosition()]=isChecked;

                    if(lv.getChoiceMode()!=lv.CHOICE_MODE_MULTIPLE){
                        lv.setChoiceMode(lv.CHOICE_MODE_MULTIPLE);
                    }
                    lv.setItemChecked(c.getPosition()+1,isChecked);
                    log(isChecked+" selected "+(c.getPosition()+1));
                }

        };
        }

        CheckBox cb= (CheckBox) aView;
        cb.setOnCheckedChangeListener(chkL);

        return (i==0);
    }};

目前,我正在尝试通过按下复选框来至少使该项目“被选中”。我正在使用c.getPosition()+1(cursor's position) 来获取被点击的列表项的位置。但这似乎总是返回1或有时返回随机值。

更新: 看起来它总是返回 1,但是当我遍历 getCheckedItemPositions() 时,我看到那个项目没有。10人被选中。点击另一个复选框,光标位置再次为 1,但第 11 项将被选中,依此类推。但是,如果我在复选框之外点击,则会选择正确的项目。

此外,在选择一个复选框时,如果向下滚动,您会看到其他几个复选框已被选中。(我的列表中有大约 255 项)。我认为这是由于android重用相同复选框的方式?

4

1 回答 1

0

我会尝试一种稍微不同的方法:

  • 将 ListView 保持为SINGLE_CHOICE,但使用侦听器设置每行的 CheckBox,该侦听器将行添加/删除id到名为 List的checkedRows(例如)。

  • 当您想要删除、移动、加注星标等选中的行时:迭代checkedRows并执行必要的操作。

我相信这比在多种类型的默认状态和功能之间来回切换更简单。

添加

我从来没有覆盖setViewValue(),但这应该工作:

CheckBox cb= (CheckBox) aView;
cb.setOnCheckedChangeListener(chkL);
cb.setTag(c.getLong(c.getColumnIndex("_id"))); // Add this

在你的onClickListener()

long id = (Long) cb1.getTag();
于 2012-06-03T22:08:44.990 回答