Articles → Android → Context Menu In Android

Context Menu In Android






Example




  1. Right-click on res/menu folder and click on New Menu resource file.
  2. Following window will appear.
  3. Picture showing the popup window for adding the resource file
    Click to Enlarge

  4. Enter the menu name and click on Ok.
  5. In the context_menu.xml, add the following code
  6. <?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>


  7. Next step is to create a list view and register it for context menu.
  8. 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);


  9. 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);
  }
}




Picture showing the output of the context menu in android
Click to Enlarge


Posted By  -  Karan Gupta
 
Posted On  -  Sunday, November 24, 2019

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250