Articles → Android → Create A Menu Control In Android

Create A Menu Control In Android






Steps Of Creating A Menu




  1. Create a menu folder inside the res folder.
  2. Add a file search_option.xml inside the menu folder.
  3. Picture showing the search_option.xml file added inside the menu folder
    Click to Enlarge

  4. Add following code in search_option.xml
  5. <?xml version="1.0" encoding="utf-8"?>
    <menu
    	xmlns:android="http://schemas.android.com/apk/res/android"
    	xmlns:app="http://schemas.android.com/apk/res-auto">
    	<item android:id="@+id/search" android:title="Search" android:icon="@mipmap/ic_launcher_round" />
    	<item android:id="@+id/about" android:title="About" android:icon="@mipmap/ic_launcher" />
    </menu>




  6. In Java code, add following methods
  7. @Override
    public boolean onCreateOptionsMenu(Menu menu) {
      MenuInflater inflater = getMenuInflater();
      inflater.inflate(R.menu.search_option, menu);
      return true;
    }
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem 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.onOptionsItemSelected(item);
      }
    }





Output




Picture showing the android screen on load
Click to Enlarge





Picture showing the menu on the android application
Click to Enlarge



Picture showing the search button clicked in the android application
Click to Enlarge



Picture showing the about button clicked in the android application
Click to Enlarge


Submenu






<?xml version="1.0" encoding="utf-8"?>
<menu
	xmlns:android="http://schemas.android.com/apk/res/android"
	xmlns:app="http://schemas.android.com/apk/res-auto">
	<item android:id="@+id/search" android:title="Search" android:icon="@mipmap/ic_launcher_round">
		<menu>
			<item android:id="@+id/create_new" android:title="Create New" />
		</menu>
	</item>
	<item android:id="@+id/about" android:title="About" android:icon="@mipmap/ic_launcher" />
</menu>




Picture showing the submenu in android application
Click to Enlarge



Picture showing the search button clicked in the android application
Click to Enlarge


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

Query/Feedback


Your Email Id
 
Subject
 
Query/FeedbackCharacters remaining 250