OptionsMenu

In this tutorial we are going to create two types of options menu in android. First one is which there is 3 dots is present in actionbar and if you click that it will show a popup menu with a list of actions.

You can create a menu by right clicking on the res folder then android resource file. Give the name menu and set resource type menu

Step 01

Step 02

Your menu file should look like this

menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item
        android:id="@+id/settings"
        android:title="Settings" />
</menu>

Now inside MainActivity implement onCreateOptionsMenu and onOptionsItemSelected methods or you can simply add below code to MainActivityFile below onCreate Method.

MainActivity.java
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.menu, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle item selection
    switch (item.getItemId()) {
        case R.id.settings:
            Toast.makeText(this, "clicked settings", Toast.LENGTH_SHORT).show();
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

If you have a one menu item then it is best practice to show it directly on toolbar with an icon like below

First we need the settings icon you see above for that right click on drawable -> new -> vector asset. click on the android icon and search for settings and make sure to select white color and atlast add it to drawable. now in our menu.xml file add following code.

menu.xml
<?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/settings"
        app:showAsAction="always"
        android:icon="@drawable/ic_settings_black_24dp"
        android:title="Settings" />
</menu>

Now if you run you will get something like this

Complete code here

Last updated