如何从动作模式和可扩展列表视图中选择项目?

时间:2014-01-17 12:21:52

标签: android

我有一个ExpandableListView,我想在用户长按和项目时启用动作模式。我已设法使动作模式有效,但当我试图知道选择了哪个项目时问题就出现了。这是我的片段的代码,在onItemLongClick函数中我尝试选择用户长按的元素(我虽然ExpandibleListView会单独执行此操作),然后在ActionMode.Callback我尝试获取所选元素,但我总是得到一个null。问题出在哪儿?我该怎么做才能让它发挥作用?

提前致谢!

public class OverviewFragment extends Fragment{
    private ExpandableListView listViewTimeslips;
    private ActionMode mActionMode;
    private ActionMode.Callback mActionModeCallback = new ActionMode.Callback(){
        @Override
        public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
            switch (item.getItemId()) {
            case R.id.action_edit:
                //HERE I GET A NULL
                Timeslip timeslip = (Timeslip)listViewTimeslips.getSelectedItem();
                mode.finish(); // Action picked, so close the CAB
                return true;
            case R.id.action_remove:
               mode.finish(); // Action picked, so close the CAB
               return true;
           default:
               return false;
       }
      //MORE CODE
    };

  }
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    listViewTimeslips.setOnItemLongClickListener(new OnItemLongClickListener(){
        @Override
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
            if(mActionMode!=null){
                return false;
            }
            if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
                int groupPosition = ExpandableListView.getPackedPositionGroup(id);
                int childPosition = ExpandableListView.getPackedPositionChild(id);

                ((ExpandableListView)parent).setSelectedChild(groupPosition, childPosition, true);
            }
            mActionMode = ((ActionBarActivity)getActivity()).startSupportActionMode(mActionModeCallback);
            view.setSelected(true);
        }

    });

1 个答案:

答案 0 :(得分:1)

好的,我终于成功了。我所做的是在onItemLongClick方法中添加以下行:

listViewTimeslips.setItemChecked(position, true);

然后,onActionItemClicked内的ActionMode.Callback()

int pos = listViewTimeslips.getRefreshableView().getCheckedItemPosition();
Timeslip timeslip = (Timeslip)listViewTimeslips.getItemAtPosition(pos);