How to retrieve the listview selected item in Contextual Action Bar

3k views Asked by At

I'm using Contextual Action Barwith ListView (CHOICE MODE SINGLE). Everything works but I don't know how to retrieve the selected item.

listViewData.setChoiceMode(ListView.CHOICE_MODE_SINGLE);

listViewData.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            if (mActionMode != null) {
                return false;
            }

            mActionMode = ((ActionBarActivity) getActivity()).startSupportActionMode(mActionModeCallback);
            view.setSelected(true);
            return true;
        }
});

private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
    @Override
    public boolean onCreateActionMode(ActionMode mode, Menu menu) {
        MenuInflater inflater = mode.getMenuInflater();
        inflater.inflate(R.menu.context_menu, menu);
        return true;
    }

    @Override
    public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
        return false;
    }

    @Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {

        switch (item.getItemId()) {
            case R.id.menu_edit:
                mode.finish();
                return true;
            case R.id.menu_share:
                mode.finish();
                return true;
            case R.id.menu_delete:
                mode.finish();
                return true;
            default:
                return false;
        }
    }

    @Override
    public void onDestroyActionMode(ActionMode mode) {
        mActionMode = null;
    }
};
1

There are 1 answers

0
ρяσѕρєя K On BEST ANSWER

how to retrieve the selected item

you can use ActionMode.setTag() in onItemLongClick to pass selected item position to onActionItemClicked using ActionMode.getTag() as :

mActionMode = ....;
mActionMode.setTag(position);  //<<< set selected row position
view.setSelected(true);

and set selected item in onActionItemClicked :

@Override
    public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            int item_postion=Integer.parseInt(mode.getTag().toString());
            String str_item=listViewData.getAdapter().getItem(item_postion);
            ....
      }