Add a menu to an empty activity

Craig Gallagher picture Craig Gallagher · Mar 18, 2016 · Viewed 51.7k times · Source

I have made an android application in Android Studio and would like to create a option menu on it. I created it as an empty activity and now realize I would have been better creating a blank activity to get the option menu. Is there anyway to create the option menu in a empty activity. If someone could point me to a tutorial that would be great this is my code so far for my menu.

menu_menu

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="saveourcar.soc.MainActivity">
    <item
        android:id="@+id/action_Menu"
        android:orderInCategory="100"
        android:title="Menu"
        app:showAsAction="never" >
    <menu>
        <item
            android:id="@+id/instructions"
            android:title="Instructions"
            android:icon="@drawable/bg"/>
        <item
            android:id="@+id/hotels"
            android:title="Hotels"
            android:icon="@drawable/mechanic"/>

    </menu>
    </item>
</menu>

Main activity

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_Menu) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

Answer

Zaid Qureshi picture Zaid Qureshi · Mar 18, 2016

You need to inflate your menu. These tutorials show how to use menus. So something like this, and choose a better name than menu_menu:

public boolean onCreateOptionsMenu(Menu menu) {
 MenuInflater inflater = getMenuInflater();
 inflater.inflate(R.menu.menu_menu, menu);
 return true;
}