Open In App

How to Apply onClickListener on Menu Item in Android?

In the context of Android development, a “menu item” refers to an individual item in a menu. A menu is a visual element in an Android app that provides a set of options to the user, allowing them to perform various actions or navigate to different parts of the app.

A menu item is typically represented by an icon or text, or both, and when selected by the user, it triggers a specific action or opens a new screen. The menu items in an Android app can be displayed in a number of ways, including as a context menu, an options menu, or an action bar. In Android, menu items are defined in an XML file and can be inflated in the app’s code to create the menu dynamically at runtime. The XML file defines the structure of the menu, including the text or icons that should be displayed for each menu item and the actions that should be taken when each item is selected. Now see how can we apply OnClick Listener to these menu items:



  1. Inflate the menu: In your Activity class, override the onCreateOptionsMenu method and use the MenuInflater class to inflate the menu resource file into the Menu object passed as a parameter.
  2. Identify the menu item: Use the findItem method to retrieve a reference to the desired menu item.
  3. Set an onClick listener: Use the setOnMenuItemClickListener method to set an onClick listener on the menu item.

Step by Step Implementation

Step 1: Create a New Project in Android Studio

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.



Step 2: Change the StatusBar Color

Navigate to app > res > values > themes > themes.xml and add the below code under the style section in the themes.xml file.

<item name="android:statusBarColor" tools:targetApi="l">#308d46</item>

Step 3: Creating a menu layout for the menu item

In this step, we are going to create the menu button that is displayed in the action bar. Navigate to app > res > create a new directory named menu then inside the menu folder create a new layout file named menu_items.xml. Below is the code for it.




<?xml version="1.0" encoding="utf-8"?>
    <item
        android:id="@+id/action_add_btn"
        android:icon="@drawable/ic_btn_menu"
        android:orderInCategory="100"
        android:title="btn"
        app:showAsAction="always" />
</menu>

This XML code defines a menu with a single menu item with an icon, text label, and order, and that should always be visible on the action bar.

Step 4: Working with MainActivity

In this article, we are going to inflate the menu_items layout file and apply OnclickListener to it. Navigate to app > java > your package name > MainActivity. Below is the code for MainActivity.




package com.example.geeksforgeeks
 
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
 
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
 
    // Inflating the menu items from the menu_items.xml file
    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_items, menu)
        return super.onCreateOptionsMenu(menu)
    }
 
    // Handling the click events of the menu items
    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        // Switching on the item id of the menu item
        when (item.itemId) {
            R.id.action_add_btn -> {
                // Code to be executed when the add button is clicked
                Toast.makeText(this, "Menu Item is Pressed", Toast.LENGTH_SHORT).show()
                return true
            }
        }
        return super.onOptionsItemSelected(item)
    }
}




package com.example.geeksforgeeks;
 
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
 
public class MainActivity extends AppCompatActivity {
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
 
    // Inflating the menu items from the menu_items.xml file
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_items, menu);
        return super.onCreateOptionsMenu(menu);
    }
 
    // Handling the click events of the menu items
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Switching on the item id of the menu item
        switch (item.getItemId()) {
            case R.id.action_add_btn:
                // Code to be executed when the add button is clicked
                Toast.makeText(this, "Menu Item is Pressed", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

Output:


Article Tags :