Loading...

Wednesday, 26 September 2012

Create Menu in Android App

// Here is the java code in Main.java
package com.test.menu;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.view.MenuInflater;
import android.view.MenuItem;

public class Main extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public boolean onCreateOptionsMenu(android.view.Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_main, menu);
        return true;
    }
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
        case R.id.game:
            // code
            NewGame(); // start new activity
            return true;
        case R.id.help:
            // code
            Help(); // start new activity
            return true;
        case R.id.exit:
            // code
            finish(); // exit from the activity
            return true;           
        default:
            return super.onOptionsItemSelected(item);
        }

    }
}

// activity_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <group android:checkableBehavior="single" >
        <item
            android:id="@+id/game"
            android:title="@string/game"/>
        <item
            android:id="@+id/help"
            android:title="@string/help"/>
        <item
            android:id="@+id/exit"
            android:title="@string/exit"/>

    </group>

</menu>

// string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Test Menu</string>
    <string name="game">New game</string>
    <string name="help">Help</string>
    <string name="exit">Exit</string>
</resources>

No comments:

Post a Comment