Search code examples
androidandroid-layoutandroid-studioandroid-manifestoncreateoptionsmenu

Implementing an option menu in Android Studio


How do I implement an option menu in my android application? I tried code from Android Developer but I get errors. Such as these: Element menu must be declared. Here is my code

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/new_game"
    android:icon="@drawable/ic_new_game"
    android:title="@string/new_game"
    android:showAsAction="ifRoom"/>
<item android:id="@+id/help"
    android:icon="@drawable/ic_help"
    android:title="@string/help" />
</menu>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lucavanraalte.test" >

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >

    <activity android:name=".MainActivity" android:screenOrientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

    </activity>
</application>

</manifest>

enter image description here


Solution

  • In your java code, add this onCreateOptionsMenu to show optionMenu,

    @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            MenuInflater inflater = getMenuInflater();
            inflater.inflate(R.menu.option_menu, menu); //your file name
            return super.onCreateOptionsMenu(menu);
        }
    

    Keep your under res\menu\option_menu folder,

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/new_game"
        android:icon="@drawable/ic_new_game"
        android:title="@string/new_game"
        android:showAsAction="ifRoom"/>
    <item android:id="@+id/help"
        android:icon="@drawable/ic_help"
        android:title="@string/help" />
    </menu>
    

    Now, if you want to set onOptionsItemSelected i.e onClick event for that ou can use,

    @Override
        public boolean onOptionsItemSelected(final MenuItem item) {
    
            switch (item.getItemId()) {
                case android.R.id.new_game:
                    //your code
                    // EX : call intent if you want to swich to other activity 
                    return true;
                case R.id.help:
                    //your code
                    return true;
                default:
                    return super.onOptionsItemSelected(item);
            }
        }