1. Create an Options Menu using the below Items for the XML file.
Name: cmenu_action1
Title: Action 1
Name: cmenu_action2
Title: Action 2Name: cmenu_action3
Title: Action 3
2. Ensure your minSdkVersion is 11, or greater. ActionMode was added in API level 11.
3. Open MainActivity.java file and add below lines to import section.
import android.view.ActionMode;
import android.view.MenuItem;
import android.view.ActionMode;
import android.view.View.OnLongClickListener;
4. Add the below 2 bolded lines between the public class and the onCreate method.
public
class
MainActivity
extends
Activity {
ActionMode.Callback mCallback;
ActionMode mMode;
@Override
public
void
onCreate(Bundle savedInstanceState) {
5. Add this callback to your onCreate method. Make sure to add a Toast import.
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCallback =
new
ActionMode.Callback() {
@Override
public
boolean
onPrepareActionMode(ActionMode mode, Menu menu) {
return
false
;
}
@Override
public
void
onDestroyActionMode(ActionMode mode) {
mMode =
null
;
}
@Override
public
boolean
onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle(
"1 selected"
);
getMenuInflater().inflate(R.menu.context_menu, menu);
return
true
;
}
@Override
public
boolean
onActionItemClicked(ActionMode mode, MenuItem item) {
switch
(item.getItemId()){
case
R.id.cmenu_action1:
Toast.makeText(getBaseContext(),
"Selected Action1 "
, Toast.LENGTH_LONG).show();
mode.finish();
break
;
case
R.id.cmenu_action2:
Toast.makeText(getBaseContext(),
"Selected Action2 "
, Toast.LENGTH_LONG).show();
break
;
case
R.id.cmenu_action3:
Toast.makeText(getBaseContext(),
"Selected Action3 "
, Toast.LENGTH_LONG).show();
break
;
}
return
false
;
}
};
OnLongClickListener listener =
new
OnLongClickListener() {
@Override
public
boolean
onLongClick(View v) {
if
(mMode!=
null
)
return
false
;
else
mMode = startActionMode(mCallback);
return true;
}
};
Resources:
http://developer.android.com/design/patterns/actionbar.html
http://wptrafficanalyzer.in/blog/creating-a-contextual-menu-bar-contextual-action-mode-for-a-single-view-in-android/
http://developer.android.com/reference/android/view/ActionMode.html