Search code examples
androidactionmode

How to prevent close action mode when no item is selected


I used action mode to show selection mode, but when the selected item count is 0, it will auto exit action mode. I want to keep in selection mode unless user press back key.

ModeCallback mModeCallBack = new ModeCallback();
mGridview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mGridview.setMultiChoiceModeListener(mModeCallBack);

private class ModeCallback implements GridView.MultiChoiceModeListener {
...
}

Solution

  • I have fixed this issue.

    @Override
    public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
        ...
        mCheckedCount = mGridview.getCheckedItemCount();
        // if we unselect the last item, cout is 0, we set it to -1, so it will not exit action mode(because if cout==0, mode.finish()).
        // if we select 1 item, we should plus this "1" back. unless the count will be woring.
        if (mCheckedCount == 0) {
            Utils.modifyFileValue(mGridview, "mCheckedItemCount", mCheckedCount + (checked ? 1 : -1));
        }
    
        String title = "";
        // we must get the count again, because we changed it.
        mCheckedCount = mGridview.getCheckedItemCount();
        title = mContext.getResources().getString(R.string.select_albums, mCheckedCount > 0 ? mCheckedCount : 0);
    
        mSelectedConvCount.setText(title);
    
        ....
    
        if (checked) {
            mSelectedIds.add(selectedId);
        } else {
            mSelectedIds.remove(selectedId);
        }
    }
    
    public static void modifyFileValue(Object object, String filedName, int filedValue) {
        //for my case, I want to get mCheckedItemCount in AbsListView.class, but i passed Gridview, so it should getSuperclass(). because GridView don't have mCheckedItemCount.
        Class classType = object.getClass().getSuperclass();
        Field fild = null;
        try {
            fild = classType.getDeclaredField(filedName);
            fild.setAccessible(true);
            fild.set(object, filedValue);
        } catch (NoSuchFieldException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }