02
Dec
10

Opening a New Activity in Android


This page describes the process of creating an Android application that will present the user with a Navigation Menu. When the user clicks they will be directed to either the “Product” or “Location” page. The “breakout” pages will have a back button that allows the user to return to the main menu.

Full downloadable source for this page is available here. Corrections and enhancements are welcome, fork, change and push back to GitHub.

Background

This page Covers:

  • Page Layouts
  • Creating ListView with menu items and icons
  • Creating Buttons and defining onClickListeners
  • Creating and starting Activities using Intents

Requirements

Create a new Project

  1. In eclipse Right click New -> project, choose ?Android Project?
  2. Project Name: AndroidNav
  3. Package name: com.test
  4. Create Activity: MainMenuActivity
  5. Click Finish

Define the Resources

Define the resource strings

res/values/strings.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="app_name">Custom Navigation Main Menu</string>
    <string name="product">Product</string>
    <string name="locations">Locations</string>
</resources>

Layout Files

Main Menu Activity presents a ListView containing 2 choices. Each item in the list has an icon to the left and to the right of the text. When the user clicks on the item a new page displays.

/res/layout/main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     
    <ListView android:id="@+id/ListView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">       
    </ListView>
 
</LinearLayout>

Each row of the ListView seen above is defined by the following xml file. Each row contains an icon to the left and right of the text. An additional LinearLayout was required to get the icon to align/justify to the right.

/res/layout/row.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="horizontal">
     
    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:src="@drawable/ic_launcher"/>
 
    <TextView
        android:id="@+id/toptext"
        android:padding="5dp"
        android:textSize="10pt"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent" />
     
    <LinearLayout
        android:layout_width="fill_parent" android:layout_height="fill_parent"     
        android:orientation="horizontal"
        android:gravity="right|center_vertical">
        <ImageView      
            android:id="@+id/navIcon"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"           
            android:src="@android:drawable/ic_media_play"          
            />
    </LinearLayout>
                         
</LinearLayout>

The Product and the Location page are the “breakout” pages. They have a back button on the bottom.

/res/layout/product.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     
    <TextView android:text="Product Menu" android:textSize="15pt"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="1" />
 
    <Button android:id="@+id/productReturnToMainButton"
    android:layout_height="wrap_content"
        android:text="&lt; Back to Main Menu"
        android:layout_centerInParent="true"
        android:layout_width="fill_parent"></Button>
 
</LinearLayout>

/res/layout/locations.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     
    <TextView android:text="Locations" android:textSize="15pt"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:layout_weight="1" />
 
    <Button android:id="@+id/locationReturnToMainButton"
    android:layout_height="wrap_content"
        android:text="&lt; Back to Main Menu"
        android:layout_centerInParent="true"
        android:layout_width="fill_parent"></Button>
 
</LinearLayout>

Activity Classes

The following is the main activity class. This class listens to events from the ListView. It contains a switch statement that directs the user to the appropriate page based on their selection. I know its not really the best way to do it, if you guys have a suggestion to improve it please post a comment.

src/com/test/MainMenuActivity.java

package com.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
 
public class MainMenuActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
 
        setTitle("Custom Navigation Main Menu");
         
        //get the reference to the list view defined in main.xml layout.
        final ListView listView = (ListView)findViewById(R.id.ListView01);
         
        listView.setAdapter(new ArrayAdapter<String>(this, R.layout.row,
                R.id.toptext, new String[] {
                        getResources().getString(R.string.product),
                        getResources().getString(R.string.locations) }));
         
        listView.setOnItemClickListener(new OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                switch(position) {
                case 0:
//                    Toast.makeText(getApplicationContext(),
//                            "Product List Item was clicked.",
//                            Toast.LENGTH_SHORT).show();
                    startActivity(new Intent(getApplicationContext(),
                            ProductMenuActivity.class));
                    break;
                case 1:
//                    Toast.makeText(getApplicationContext(),
//                            "Locations List Item was clicked.",
//                            Toast.LENGTH_SHORT).show();                            
                    startActivity(new Intent(getApplicationContext(),
                            LocationMenuActivity.class));
                    break;
                }
            }
        });
    }
}

The following two activities are very similar. The implementation of the Back functionality in both are done by calling finish(). This might not be the best way of doing it since the main menu could have already been killed by android to re-claim memory.

src/com/test/LocationMenuActivity.java

package com.test;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class LocationMenuActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.locations);
        Button returnToMainButton = (Button)findViewById(R.id.locationReturnToMainButton);
        if(returnToMainButton!=null) {
            returnToMainButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });       
        }
    }
}

src/com/test/ProductMenuActivity.java

package com.test;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
 
public class ProductMenuActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
         
        setContentView(R.layout.product);
         
        Button returnToMainButton = (Button)findViewById(R.id.productReturnToMainButton);
        if(returnToMainButton!=null) {
            returnToMainButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });       
        }
    }
}

Android Manifest

The manifest file contains definitions for:

  1. Application Name (Label)
  2. Icon that represents the application
  3. Each Activity
  4. The “Main” Activity that will run when the application starts

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test"
      android:versionCode="1"
      android:versionName="1.0">
      
        <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="19" />
        
    <application android:icon="@drawable/ic_launcher" android:label="@string/app_name">
        <activity android:name=".MainMenuActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ProductMenuActivity"
                  android:label="@string/app_name">
        </activity>
        <activity android:name=".LocationMenuActivity"
                  android:label="@string/app_name">
        </activity>
    </application>
</manifest> 
Full downloadable source for this page is available here.
Advertisements

1 Response to “Opening a New Activity in Android”


  1. 1 RandyL
    February 8, 2011 at 9:28 pm

    Thanks. This example has shown me how to bind an action to a listview and has given me a direction on my own app. Thanks for the excellent example.


Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Enter your email address to subscribe to this blog and receive notifications of new posts by email.

Join 77 other followers

December 2010
S M T W T F S
« Nov   Jan »
 1234
567891011
12131415161718
19202122232425
262728293031  

Blog Stats

  • 830,829 hits

%d bloggers like this: