In this post we want to analyze the Android ListView context menu (contextual actionbar). A contextual actionbar is a menu that is activated when user long press on a specific item. The contextual menu can be applied to almost all views but it is usually used with ListView.
You will learn:
Contextual action mode
How to use Long click: onItemLongClickListener
We talk a lot about List view, because it is one of the most important component. We can distinguish two different type of contextual menu:
- Floating menu
- Contextual action mode (ActionMode)

Create contextual action Mode: Define ActionMode.CallBack interface
public boolean onPrepareActionMode(ActionMode mode, Menu menu)
return false;
}
public void onDestroyActionMode(ActionMode mode) {
mode = null;
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
}
};
[/java]
<item android:id=”@+id/edit”
android:icon=”@android:drawable/ic_menu_edit”/>
<item android:id=”@+id/delete”
android:icon=”@android:drawable/ic_menu_delete”/>
</menu>
[/xml]
mode.setTitle(“Options”);
mode.getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
[/java] Now we have to show this contextual action bar when user long clicks on an item.
Android ListView Context menu: ActionMode and Long Click
If we want to show this contextual bar when user long clicks we have simply set a listener on our ListView, that we call lv in the source code. So we have:
[java]lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick (AdapterView parent, View view, int position, long id) {
System.out.println(“Long click”);
startActionMode(modeCallBack);
view.setSelected(true);
return true;
}
});
[/java]
In line 4 we simply start the contextual menu using startActionMode method. Now the result is:
Contextual menu item selection
int id = item.getItemId();
switch (id) {
case R.id.delete: {
aAdpt.remove( aAdpt.getItem(aAdpt.currentSelection) );
mode.finish();
break;
}
case R.id.edit: {
System.out.println(” edit “);
break;
}
default:
return false;
}
[/java]
In line 6 we simply remove from our adapter the selected item. To know the position of the selected item inside the ListView we store it in the OnItemLongClickListener method.
[java]aAdpt.currentSelection = position;[/java]
When we finish handling user menu item selection we have to dismiss the contextual action bar calling mode.finish (line 7). At the end of this post you gained the knowledge how to activate Android ListView context menu.
very nice tutorial you can also check this one
http://pavanhd.blogspot.in/2013/02/android-context-menu-example.html
http://stackoverflow.com/questions/25317347/android-cant-click-listview-action-mode-items?sgp=2
we need to download API 11 ?
we need to download API 11 ?
Thanks for sharing this great information. This is a great list for those people who looking Corporate Themes to build their website.