如何在没有长按事件的情况下触发Android中的上下文操作栏(CAB),以便从Android中的ListView中选择多个项目

时间:2016-08-24 11:26:32

标签: java android listview contextual-action-bar

我刚刚学会了如何创建listview,但不知道如何选择多个项目而不用长按任何项目。我想在操作栏中按“选择”按钮后触发CAB,然后删除所选项目。以下是来自developer.android.com的长按事件的代码:

ListView listView = getListView();
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {

    @Override
    public void onItemCheckedStateChanged(ActionMode mode, int position,
                                          long id, boolean checked) {
        // Here you can do something when items are selected/de-selected,
        // such as update the title in the CAB
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
        // Respond to clicks on the actions in the CAB
        switch (item.getItemId()) {
            case R.id.menu_delete:
                deleteSelectedItems();
                mode.finish(); // Action picked, so close the CAB
                return true;
            default:
                return false;
        }
    }

    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        // Inflate the menu for the CAB
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.context, menu);
        return true;
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        // Here you can make any necessary updates to the activity when
        // the CAB is removed. By default, selected items are deselected/unchecked.
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        // Here you can perform updates to the CAB due to
        // an invalidate() request
        return false;
    }
})

1 个答案:

答案 0 :(得分:0)

http://www.technotalkative.com/contextual-action-bar-cab-android/

tldr;

1)实现ActionMode.Callback接口。

2)要显示该栏时,请调用startActionMode()。