CursorAdapter打破了CHOICE_MODE_MULTIPLE选项

时间:2012-08-14 13:57:25

标签: android listview android-arrayadapter android-cursoradapter

我有ListFragment,我在CursorAdapter添加ListView,我希望能够点击多行,以使用上下文操作栏。我使用SherlockActionbar,当我使用简单的ArrayAdapter时,它工作正常。但当我切换到CursorAdapter时,它会中断。我不能选择多行,只能选择一行。知道为什么会这样吗?

onActivityCreated我设置了列表:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mActionMode = null;
    mListView = getListView();
    FinTracDatabase database = mDatabaseProvider.get();
    Cursor cursor = database.getTransactionCursor(false);
    mCursorAdapter = new TransactionListAdapter(getSherlockActivity(), cursor);
    mListView.setAdapter(mCursorAdapter);
    mListView.setItemsCanFocus(false);
    mListView.setOnItemClickListener(this);
    mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}

这是我的Adapter

private class TransactionListAdapter extends CursorAdapter {

    public TransactionListAdapter(Context context, Cursor cursor) {
        super(context, cursor, 0);
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        bindToExistingView(view, cursor);
    }

    private void bindToExistingView(View view, Cursor cursor) {
        CheckedTextView amountView = (CheckedTextView) view;
        amountView.setText(cursor.getString(cursor.getColumnIndex(Transactions.TITLE)));
    }

    @Override
    public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
        LayoutInflater layoutInflater = getSherlockActivity().getLayoutInflater();
        View view = layoutInflater.inflate(android.R.layout.simple_list_item_multiple_choice, arg2, false);
        bindToExistingView(view, arg1);
        return view;
    }

}

最后是onClickListener:

@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
    SparseBooleanArray checked = mListView.getCheckedItemPositions();
    boolean hasCheckedElement = true;
    for (int i = 0; i < checked.size() && !hasCheckedElement; i++) {
        hasCheckedElement = checked.valueAt(i);
    }

    if (hasCheckedElement) {
        if (mActionMode == null) {
            mActionMode = getSherlockActivity().startActionMode(new SelectingActionMode());
        }
    } else {
        if (mActionMode != null) {
            mActionMode.finish();
        }
    }
}

如果我将我的适配器切换到一个简单的ArrayAdapter,它可以正常工作。

new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_multiple_choice, new String[]{"A", "B", "C"})

我无望,我不知道,为什么会这样。

1 个答案:

答案 0 :(得分:2)

为了使ListView.CHOICE_MODE_MULTIPLE模式正常工作,适配器中的每个项都必须从getItemId()方法返回唯一值。

您在适配器上使用的光标是在以下行中生成的:

  FinTracDatabase database = mDatabaseProvider.get();
  Cursor cursor = database.getTransactionCursor(false);

您可以检查每行的“_id”列是否包含唯一值?我怀疑它们都共享相同的值,导致你看到的行为。