如何在上下文操作栏中检索列表视图选定项

时间:2013-12-04 01:21:46

标签: android listview contextual-action-bar

我正在使用带有ListView的上下文操作栏(CHOICE MODE SINGLE)。一切正常但我不知道如何检索所选项目。

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 个答案:

答案 0 :(得分:9)

  

如何检索所选项目

您可以使用onItemLongClick中的ActionMode.setTag()将所选项目位置传递给onActionItemClicked,使用ActionMode.getTag()作为:

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

并在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);
            ....
      }