Android Development masterclass
It’s time to go beyond the ‘hello world’ app. Let’s look into real-world situations and start doing big things with your Android development project…
Adding menu buttons
Menus are implemented a bit differently than on other platforms. Menus are mostly in the form of an on-screen icon array which opens when the physical Menu button is pressed on an Android device. Each application has its own set of menus, which provides access to the main application features. In this demo we will learn how to add menu buttons to an Android app.
The first step is to add the necessary UI elements, in this case Menu. Create a folder called ‘menu’ (make sure it is lower case) inside the ‘res’ folder of your project. Then create a new Android XML file of type menu and name it menu.xml. You also create a plain XML file menu.xml and do the following:
@code: res/menu/menu.xml
<?xml version=”1.0” encoding=”utf-8”?> <menu xmlns:android=”http://schemas.android.com/apk/res/android”> <item android:id=”@+id/imgButton” android:icon=”@drawable/icon” android:title=”Image Button”></item> <item android:id=”@+id/txtButton” android:title=”Text Button”></item> </menu>
Now, we need to override the following functions …
onCreateOptionsMenu: This initialises the contents of the Activity’s standard options menu. We will be overriding it to include our own menu items.
onOptionsItemSelected: This hook is called whenever an item in your options menu
is selected.
@code
package com.ludmenubutton;
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 MainActivity 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.menu.menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
case R.id.imgButton:
Toast.makeText(this, “Image Button Pressed”, Toast.LENGTH_SHORT).show();
break;
case R.id.txtButton:
Toast.makeText(this, “Text Button Pressed”,Toast.LENGTH_SHORT).show();
break;
}
return true;
}
}
You can find more Linux User & Developer tutorials here, or click here to see what else was in issue 89.















An alternative to your ProgressBar approach is AsyncTask and onProgressUpdate: http://developer.android.com/reference/android/os/AsyncTask.html
Keep up the Android articles.