2

如果AbsListView.setItemChecked()直接调用,效果很好,ActionMode会激活并创建。

mGridView.setItemChecked(pPosition, true);

但是当你View.startActionMode()先调用,然后调用AbsListView.setItemChecked()时,ActionModecreate bystartActionMode()将销毁,并重新创建一个新的 by setItemChecked()

我的问题是:第一次打电话时如何避免这个问题View.startActionMode()

期待你的答复!谢谢!

4

1 回答 1

1

为什么要重新创建一个新的?查看方法的源码AbsListView.setItemChecked(int position, boolean value),可以看到如下代码:</p>

    // Start selection mode if needed. We don't need to if we're unchecking something.
    if (value && mChoiceMode == CHOICE_MODE_MULTIPLE_MODAL && mChoiceActionMode == null) {
        if (mMultiChoiceModeCallback == null ||
                !mMultiChoiceModeCallback.hasWrappedCallback()) {
            throw new IllegalStateException("AbsListView: attempted to start selection mode " +
                    "for CHOICE_MODE_MULTIPLE_MODAL but no choice mode callback was " +
                    "supplied. Call setMultiChoiceModeListener to set a callback.");
        }
        mChoiceActionMode = startActionMode(mMultiChoiceModeCallback);
    }

这意味着如果mChoiceActionMode == null,它将调用startActionMode(mMultiChoiceModeCallback),因此将重新创建一个新的 ActionMode。

以及如何解决?这是一个简单的方法:使用反射将ActionMode create by 分配给.startActionMode()中的私有字段mChoiceActionModeAbsListView

private void startActionMode() {
    // Get the field "mMultiChoiceModeCallback" instance by reflect
    AbsListView.MultiChoiceModeListener wrapperIns = null;
    try {
        Field wrapper = null;
        wrapper = AbsListView.class.getDeclaredField("mMultiChoiceModeCallback");
        wrapper.setAccessible(true);
        wrapperIns = (AbsListView.MultiChoiceModeListener) wrapper.get(mMessageGridView);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    // Start the ActionMode, but not select any item. 
    ActionMode actionMode = mMessageGridView.startActionMode(wrapperIns);
    // Assign actionMode to field "mChoiceActionMode" by reflect 
    try {
        Field mChoiceActionMode = null;
        mChoiceActionMode = AbsListView.class.getDeclaredField("mChoiceActionMode");
        mChoiceActionMode.setAccessible(true);
        mChoiceActionMode.set(mMessageGridView, actionMode);
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
}

为什么我们在这里使用包装器?因为AbsListView.setMultiChoiceModeListener(MultiChoiceModeListener listener)会包装我们的mMultiChoiceModeListener,所以我们不能不直接使用。

于 2015-03-04T09:41:55.720 回答