Javatpoint Logo
Javatpoint Logo

Kotlin Android Options Menu

Android Options Menu is the collection of menu items for an activity. Options menu allows placing actions that impact globally on the application.

Options Menu is created by overriding the onCreateOptionsMenu() function. The menu resource is inflated by and calling the inflate() method of MenuInflater class. To act on menu items, override the onOptionsItemSelected() function.

Kotlin Android Options Menu Example

In this example, we will add the options menu items on the action bar. Clicking on the menu shows the option menu items on which we can perform the relevant action.

Create an android project and select the Basic Activity. This activity auto generates codes for menu option and Toolbar.

activity_main.xml

Add the following code in the activity_main.xml file in layout directory. This code is auto-generated while creating Basic Activity.

content_main.xml

Add the following code in the content_main.xml file in layout directory. In this layout, you can place your UI components.

strings.xml

Add the following code in the strings.xml file.

menu_main.xml

Add the following code in the menu_main.xml file in menu directory. Add the item tag which creates the menu item for options menu.

MainActivity.kt

Add the following code in the MainActivity.kt class. In this class, we override the function onCreateOptionsMenu() and call the inflate() of MenuInflater class which inflates the menu and adds items to the action bar.

To perform action on each items of options, menu overrides the onOptionsItemSelected() function.

Output:

Kotlin Android Options Menu Kotlin Android Options Menu
Kotlin Android Options Menu

Creating Option Menu Using Images on Action Bar

We can also display the Options Menu as images on the Action Bar. To set image in the Options Menu add the icon attribute in the item tag as give below.

menu_main.xml


Next Topic#





Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA