I am new to Android application development.I want to develop a simple android application which contains menus.Is there any source code on internet.Can anybody tell me how should i pursue
Thanks in advance Tushar
Everything you need to know is in the Android Dev Guide.
What it comes down to - and I'm just copying relevant parts from the Android Dev guide - is creating an XML menu resource, e.g. this one, and saving it as game_menu.xml
:
<?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" />
<item android:id="@+id/help"
android:icon="@drawable/ic_help"
android:title="@string/help" />
</menu>
And then inflating it within your activity:
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.game_menu, menu);
return true;
}
When an item is clicked, you can do several actions:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.new_game:
newGame();
return true;
case R.id.help:
showHelp();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
XML CODE:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_new"
android:title="New" />
<item android:id="@+id/menu_about"
android:title="About" />
<item android:id="@+id/menu_help"
android:title="Help" />
</menu>
Main Code:
package com.menuexample;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MenuSample extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menus, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.menu_about:
Toast.makeText(MenuSample.this, "You Clicked About", 3000).show();
return true;
case R.id.menu_help:
Toast.makeText(MenuSample.this, "You Clicked Help", 3000).show();
return true;
case R.id.menu_new:
Toast.makeText(MenuSample.this, "You Clicked New", 3000).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With