I'm trying to make a contextual ActionBar
. I used the sample from the android devpage, but i still haven't got it to work. I set an eventlistener on onitemlongclick, but the setSelected(true)
doesn't seem to do anything. I know that the event is triggered, because the actionmode
is opened, but it doensn't select any item.
The longclicklistener
is in a fragment
, held by a viewpager
in an activity, which holds several instances of the fragment
. I would like to be able to select items from the pages and then do something with the selections.
My current code:
The fragment:
AdapterView.OnItemLongClickListener onLongClick = new AdapterView.OnItemLongClickListener() {
// Called when the user long-clicks on someView
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view,
int i, long l) {
MainActivity parent = (MainActivity)getActivity();
if (parent.actionMode != null) {
return false;
}
parent.actionMode = getActivity().startActionMode(parent.actionModeCallback);
view.setSelected(true);
return true;
}
};
The action mode callback in the activity
public ActionMode.Callback actionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_actionbar, menu);
return true;
}
// Called each time the action mode is shown. Always called after onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// Called when the user selects a contextual menu item
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_remove_list:
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// Called when the user exits the action mode
@Override
public void onDestroyActionMode(ActionMode mode) {
actionMode = null;
}
};