CursorAdapter 破坏了 CHOICE_MODE_MULTIPLE 选项

2024-05-05

我有一个ListFragment,我在其中添加一个CursorAdapter to my ListView,并且我希望能够单击几行以使用上下文操作栏。我使用 SherlockActionbar,当我使用一个简单的ArrayAdapter。但是当我切换到CursorAdapter,它破裂了。我无法选择多行,只能选择一行。知道为什么会发生吗?

In 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"})

我很绝望,我不知道为什么会发生这种情况。


为了ListView.CHOICE_MODE_MULTIPLE模式要正常工作,适配器中的每个项目都必须从getItemId() method.

您用于适配器的光标是在这些行上生成的:

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

您能否检查每行的“_id”列是否具有唯一值?我怀疑他们都有相同的价值观,从而导致了你所看到的行为。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

CursorAdapter 破坏了 CHOICE_MODE_MULTIPLE 选项 的相关文章

随机推荐