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:
- 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.
- Identify the menu item: Use the findItem method to retrieve a reference to the desired menu item.
- 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
<? 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/action_add_btn" android:icon = "@drawable/ic_btn_menu" android:orderInCategory = "100" android:title = "btn" app:showAsAction = "always" /> </ menu > |
- android:icon: This attribute sets the icon to be displayed for the menu item. The @drawable/ic_btn_menu reference points to a drawable resource in the app.
- android:orderInCategory: This attribute sets the order of the menu item relative to other items in the same category. Higher numbers mean the item will appear later in the menu.
- android:title: This attribute sets the text label for the menu item.
- app:showAsAction: This attribute determines how the menu item should be displayed on the screen. The value “always” means the item should always be visible on the action bar.
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.
Kotlin
package com.example.w3wiki 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) } } |
Java
package com.example.w3wiki; 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); } } } |
- onCreateOptionsMenu method: This method inflates the menu items from the menu_items.xml file using the menuInflater.inflate method and passing in the resource ID of the menu file and the menu object. The method returns the result of calling super.onCreateOptionsMenu method.
- onOptionsItemSelected method: This method handles the click events of the menu items. It switches on the item id of the menu item using a when statement and executes the code when the add button is clicked using the Toast class to display a message to the user. The method returns the result of calling super.onOptionsItemSelected method.
Output:
Contact Us