我已经用 Fragment 对其进行了测试,它可以工作。看下面的代码:
public class ContextMenuActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ContextMenuFragment content = new ContextMenuFragment();
getSupportFragmentManager().beginTransaction().add(
android.R.id.content, content).commit();
}
public static class ContextMenuFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_context_menu, container, false);
registerForContextMenu(root.findViewById(R.id.long_press));
return root;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
new MenuInflater(getActivity().getApplication()).inflate(R.menu.menu, menu);
menu.add(777, 0, Menu.NONE, "Menu A");
menu.add(777, 1, Menu.NONE, "Menu B");
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 0:
Log.i("ContextMenu", "Item 1a was chosen");
Log.i("ContextMenu", "group: " + item.getGroupId());
return true;
case 1:
Log.i("ContextMenu", "Item 1b was chosen");
Log.i("ContextMenu", "group: " + item.getGroupId());
return true;
case R.id.edit:
Log.i("ContextMenu", "Item Edit was chosen");
Log.i("ContextMenu", "group: " + item.getGroupId());
return true;
case R.id.delete:
Log.i("ContextMenu", "Item Delete was chosen");
Log.i("ContextMenu", "group: " + item.getGroupId());
return true;
}
return super.onContextItemSelected(item);
}
}
}
`
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<group android:id="@+id/menu_group">
<item android:id="@+id/edit"
android:title="Edit"
android:orderInCategory="0"
android:menuCategory="system" />
<item android:id="@+id/delete"
android:title="Delete"
android:orderInCategory="0"
android:menuCategory="system" />
</group>
</menu>