Reputation: 15718
So, I know we need to pass a view to openContextMenu(view); but where can i get the view for Menuitem, please have a look at my code. Thanks in advance.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.actionmenu:
openContextMenu(item); //I dont know what to pass here
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.setHeaderTitle("Select The Action");
menu.add(0, 0, 11, "Edit");
menu.add(0, 1, 12, "Delete");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
System.out.println(item.getItemId());
return super.onContextItemSelected(item);
}
Upvotes: 0
Views: 822
Reputation: 1933
By default, a long-press on a view does not trigger the creation of a context menu. You must register a view for a floating context menu by calling the following method, a listview for example:
ListView listView = (ListView) v.findViewById(android.R.id.list);
registerForContextMenu(listView);
You'd better to create a xml resource file that contains the context menu item:
your_context.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+id/context_menu_eidt"
android:title="Edit" />
<item android:id="@+id/context_menu_delete"
android:title="Delete" />
</menu>
Then inflate the resource file in onCreateContextMenu
method,
the parameter @v is the view that the context menu is being built for:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
if (v.getId() == android.R.id.list) {
Log.d(TAG, "get the view here");
}
getActivity().getMenuInflater().inflate(R.menu.your_context, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
int position = info.position;
switch (item.getItemId()) {
case R.id.context_menu_eidt:
// TODO
return true;
case R.id.context_menu_delete:
// TODO
return true;
}
return super.onContextItemSelected(item);
}
That's all.
Upvotes: 1