Home » Android

Android - Option Menu Example

In this article, we are going to learn how to create Option Menu in Android? This post contains source code files (XML, Java and Output).
Submitted by Shamikh Faraz, on March 11, 2018

Android code to create, display Option Menu - Here, we have an example, which can be used to create Option Menu in our Android project. This displays a menu which contains some options, if you click outside of displayed menu, it disappears.

1) XML File:

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

        android:text="@string/hello_world" />


2) XML File: (menu_main)

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item  android:id="@+id/item1"
    <item  android:id="@+id/item2"
    <item  android:id="@+id/item3"
        android:title="C++ 3"/>

3) Java file: (MainActivity.java)

package com.example.faraz.optionmenu_example;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);//Menu Resource, Menu
        return true;
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.item1:
                Toast.makeText(getApplicationContext(),"Android Selected",Toast.LENGTH_LONG).show();
                return true;
            case R.id.item2:
                Toast.makeText(getApplicationContext(),"Java Selected",Toast.LENGTH_LONG).show();
                return true;
            case R.id.item3:
                Toast.makeText(getApplicationContext(),"C++ Selected",Toast.LENGTH_LONG).show();
                return true;
                return super.onOptionsItemSelected(item);


When you press on particular item, it shows a toast message.

Android - Option Menu Example Output

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.