Android – Options Menu

Let’s try to learn and practice for options menu in Android Studio. This is very important part of every Android Application. We learn step by step below parts…

Step 1.

Go to Android Studio and create new empty project name it what do you want and fill all require fields like below the picture.
android optionmenu

Step 2.

Now create new menu option folder into app->res->menu.
android optionmenu

Step 3.

Now create option_menu.xml file in menu folder.
android optionmenu

Step 4.

Now copy and paste these blow codes into option_menu.xml file
<?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/main_menu1"
        android:orderInCategory="101"
        android:title="@string/menu1"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/main_menu2"
        android:orderInCategory="102"
        android:title="@string/menu2"
        app:showAsAction="never"
        />

    <item
        android:id="@+id/main_menu3"
        android:orderInCategory="103"
        android:title="@string/menu3"
        app:showAsAction="never"
        />

</menu>
Step 5.
In next step- we need to go in MainActivity.java class and then copy & paste these below java code for option_menu.
package com.android.optionmenu;

import androidx.appcompat.app.AppCompatActivity; 
import android.os.Bundle;
import android.view.Menu; 
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
 @Override
   protected void onCreate(Bundle savedInstanceState) { 
   super.onCreate(savedInstanceState); 
   setContentView(R.layout.activity_main); 
} 
@Override
   public boolean onCreateOptionsMenu(Menu menu) {
   getMenuInflater().inflate(R.menu.option_menu, menu);
 return true;
 } 
@Override
    public boolean onOptionsItemSelected(MenuItem item) { 
    int itemId = item.getItemId(); 
	System.out.println("=====> menu item:" + itemId + " selected");
	switch (itemId) 
	{ 
     case R.id.main_menu1: 
	   System.out.println("Menu1 Selected!"); 
       break;
     case R.id.main_menu2: 
       System.out.println("Menu2 Selected!");
       break;
     case R.id.main_menu3: 
	 System.out.println("Menu3 Selected!");
     break;
    }
   return super.onOptionsItemSelected(item); 
  } 
 } 
}
Step 6.
Let’s try running our app. I assume you have connected your Android mobile computer to your computer. To launch the app from Android Studio, open one of your project activity files and click “Run” on the toolbar. Choose a mobile device as an option, and then check your mobile device, which will display your default screen :-
android optionmenu