I'm trying to get a contextual menu using the Action Mode where I can select an item in a ListView by long-clicking on it. I created a MultiChoiceListener according to this reference and made a ItemLongClickListener wich sets an item as checked which is needed for the Action Mode to work according to this reference.
My problem is, that, even if the item long clicked animation is playing, the ActionMenu doesn't inflate.
ListView Code:
final ListView listView = (ListView) findViewById(android.R.id.list);
listView.setAdapter(adapter);
listView.setLongClickable(true);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
Cursor cursor = db.getSubject(id);
String subject = null;
try {
subject = cursor.getString(cursor.getColumnIndex("subject"));
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Intent intent = new Intent(Main.this, Marks.class);
intent.putExtra("selected", subject);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
listView.setItemChecked(arg2, true);
return true;
}
});
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context, menu);
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
}
});
Thanks in advance!
I do not see any code in there to actually start the action mode. That is something your OnItemLongClickListener
needs to do, such as:
@Override
public boolean onItemLongClick(AdapterView<?> view, View row,
int position, long id) {
modeView.clearChoices();
modeView.setItemChecked(position, true);
if (activeMode == null) {
activeMode=host.startActionMode(this);
}
return(true);
}
A full sample project demonstrating manually using an action mode like this can be found at: https://github.com/commonsguy/cw-omnibus/tree/master/ActionMode/Manual
Note that this project demonstrates using action modes via ActionBarSherlock.