gpt4 book ai didi

Android:AbsListView.setItemChecked() 导致 ActionMode 销毁并重新创建?

转载 作者:行者123 更新时间:2023-11-29 01:35:08 27 4
gpt4 key购买 nike

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

mGridView.setItemChecked(pPosition, true);

但是当你先调用View.startActionMode(),再调用AbsListView.setItemChecked()时,创建的ActionMode startActionMode() 将销毁,并通过 setItemChecked() 重新创建一个新的。

我的问题是:如何在调用 View.startActionMode() 时避免这个问题?

期待您的回复!谢谢!

最佳答案

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

    // 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。

如何修复?这里有一个简单的方法:使用reflect将startActionMode()创建的ActionMode赋值给AbsListView中的私有(private)字段mChoiceActionMode

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 包裹起来,所以我们不能不直接使用。

关于Android:AbsListView.setItemChecked() 导致 ActionMode 销毁并重新创建?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28756478/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com