Articles → Android → Context Menu In Android
Context Menu In Android
Example
- Right-click on res/menu folder and click on New Menu resource file.
- Following window will appear.
Click to Enlarge
- Enter the menu name and click on Ok.
- In the context_menu.xml, add the following code
<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android">
<item android:title="Search" android:id="@+id/search" />
<item android:title="About" android:id="@+id/about" />
</menu>
- Next step is to create a list view and register it for context menu.
String fruitlist[] = {
"apple",
"banana",
"orange",
"cherry"
};
ListView listView = (ListView) findViewById(R.id.listview);
ArrayAdapter < String > adapter = new ArrayAdapter < String > (this, R.layout.support_simple_spinner_dropdown_item, fruitlist);
listView.setAdapter(adapter);
registerForContextMenu(listView);
- Override onCreateContextMenu and onContextItemSelected
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(@NonNull MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item;
switch (item.getItemId()) {
case R.id.search:
Toast.makeText(EditTextDemo.this, "Search Clicked", Toast.LENGTH_LONG).show();
return true;
case R.id.about:
Toast.makeText(EditTextDemo.this, "About Clicked", Toast.LENGTH_LONG).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
Click to Enlarge