How to handle clicks on Action Bar action items?

In the previous post, I discussed how to add Action Bar in Android applications. A simple demo application was also created with dummy Action Bar (which will not respond to clicks).

Prerequisite:

You must know how to add Action Bar in Android application before you proceed with this post. I recommend you to take a look at How to add Action Bar in Android Applications? post which will provide you insights on adding Action Bar.

In this post, I will teach you how to handle clicks on Action Bar action items. You need to create a simple Android application with Action Bar before you proceed further.

Take a look at my previous post – How to add Action Bar in Android Applications? to create one.

You can download source code from here if you don’t want to create Application from scratch, otherwise please proceed with below listings.

Handling Click on actions items involves three steps, they are:

  1. When User presses an action, the system calls activity’s onOptionsItemSelected() method.
  2. Using the MenuItem passed to onOptionsItemSelected() method, get the clicked action item by using getItemId() method
  3. Perform appropriate action – Open another activity, Display Search Widget etc., based on action item value

Make sure you created simple Android application with Action Bar to proceed with below code listings. If you haven’t created it yet, please go ahead create one. Take help from this post – How to add Action Bar in Android Applications?.

Create Activities

Create two activities with Application Name ‘ProductActivity’ and ‘ContactusActivity’.

Open strings.xml present under values folder and update it with below XML:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">AndroidActionBar</string>
    <string name="hello_world">Hello world!</string>
    <string name="search">Search</string>
    <string name="products">Products</string>
    <string name="contactus">Contact Us</string>
    <string name="about">About</string>
    <string name="title_activity_product">ProductActivity</string>
    <string name="action_settings">Settings</string>
    <string name="title_activity_contactus">ContactusActivity</string>
	<string name="home">Home</string>
</resources>

Open product.xml present under menu folder and update it with below XML:

<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="com.prgguru.example.ProductActivity" >
    <item
        android:id="@+id/home"
        android:orderInCategory="100"
        android:title="@string/home"
        app:showAsAction="always"/>
</menu>

Open contactus.xml present under menu folder and update it with below XML:

<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="com.prgguru.example.ContactusActivity" >

    <item
        android:id="@+id/home"
        android:orderInCategory="100"
        android:title="@string/home"
        app:showAsAction="always"/>

</menu>
MainActivity.java

From home screen, on clicking Product action item User will be taken to ProductActivity similarly when Contact action item is clicked, User will be taken to ContactusActivity,

Action Bar Main Activity
Open MainActivity.java and update onOptionsItemSelected() method with below code:

@Override
	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();
		//When Product action item is clicked
		if (id == R.id.products) {
			//Create Intent for Product Activity
			Intent productIntent = new Intent(this,ProductActivity.class); 
			//Start Product Activity
			startActivity(productIntent);
			return true;
		}
		//When Search action item is clicked
		else if (id == R.id.search) {
			//Display Toast
			Toast.makeText(getApplicationContext(), "Search!!", Toast.LENGTH_LONG).show();
			return true;
		}
		//When Contact action item is clicked
		else if (id == R.id.contact_us) {
			//Create Intent for Contact Activity
			Intent contactusIntent = new Intent(this,ContactusActivity.class);
			//Start Contact Intent
			startActivity(contactusIntent);
			return true;
		}
		//When About action item is clicked
		else if (id == R.id.about) {
			//Display Toast
			Toast.makeText(getApplicationContext(), "This is simple Demo application with Action Bar", Toast.LENGTH_LONG).show();
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
ProductActivity.java

ProductActivity has only one action item which will navigate the User to MainActivity on clicking it.
Action_Bar_Product
Open ProductActivity.java and update method with below code:

@Override
	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();
		if (id == R.id.home) {
			Intent productIntent = new Intent(this,MainActivity.class);
			startActivity(productIntent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
ContactusActivity.java

ContactusActivity has only one action item which will navigate the User to MainActivity on clicking it.
Action_Bar_Contacus
Open ContactusActivity.java and update method with below code:

@Override
	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();
		if (id == R.id.home) {
			Intent productIntent = new Intent(this,MainActivity.class);
			startActivity(productIntent);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

Here is the screen print of the MainActivity, ProductActivity and ContactusActivity:

ActionBar Activities

[pglinkadssmall1]

Demo

That’s all. It’s time to test our code.

Run the application using emulator or device by right clicking on the project >> Run as >> Android applicaiton >> Choose emulator or device.



Download Source Code

Entire project is zipped and is available for download. Unzip the downloaded project and to import the project into eclipse, launch eclipse >> File >> Import.. >> Choose downloaded project(How to import android project in eclipse). If you just want to run the application in your mobile and see the output but don’t want to hit your head with source code, download application(apk) file and install it in your mobile device.

Download Source Code Download Application(apk)

*apk in Android  is the installation file similar to exe in windows.

[pglinkadssmall]

If you feel this article is helpful and interesting please spread a word about it to your friends and colleagues by sharing the article in Facebook or Twitter.


Share

You are always welcome to provide your comments and feedback from comment box.

Next Tutorial >> How to add Up button on Action Bar?

Reference
Handling Clicks on Action Bar
[pgwriteforus]
[pgfeedback]

Related Articles

Author: Android Guru

Share This Post On
  • J U B Sastry

    When I create the project in my latest ADT eclipse,
    the Class is naturally generated with Action Bar Activity as follows.

    public class MainActivity extends ActionBarActivity {

    Shall I keep it as it is or change it into Activity
    and then import Action Bar? If I keep it as it is, shall I use ActionBarActivity
    for the second and third activity (product and contact us) also?

    What shall I do for second and third activity if I
    change it to: public class MainActivity extends Activity? I am seeking your
    guidance since you have skipped the issue in your example on main and other
    activity files.

    • Keep ActionBarActivity as it is, it won’t create any issues. When I wrote this tutorial, ADT was not generating Activity class inheriting ActionBarActivity class. Will update this tutorial soon.

      • J U B Sastry

        thank you so much sir. I will be awaiting that.

Join now to get more access to our Android Tutorials

Join now to get more access to our Android Tutorials

Once you Join, you will receive Mail containing latest Android Tutorials once a month !!

I promise I wont spam you !!

You have Successfully Subscribed!

Pin It on Pinterest

Shares