Pr.Pg Next Pg

ListView Application Example tutorials

 

Creating a List Menu

  • Inorder to create a List Menu, in our tutorial we create a MenuList activity which extends ListActivity class.

  • We then override the methods onCreate() and onListItemClick().

  • We then define a string array name classes which holds the names of all the activities which we have created till now.

  • We then set a ListAdaptor which creates a List with the string array classes.

  • The ArrayAdaptor parameter has < type > definition where the type defines the type of data that is in the List.

  •  The reference to android.R.layout.simple_list_item_1 is simply a single TextView, so using this resource limits you to only displaying a string of text in the list item.

 

 

Starting the Activity

  • We will now start a new activity depending upon which list item is clicked.

  • The list item clicked will trigger a new Intent and the intent will in turn start the activity.

  • The OnClickListItem() method takes in parameter the postion of the item clicked, which we have used in this case to start the appropriate activity by appending that string to class path on line 24.

  • The screenshot below shows how to create a list menu and how to start a new activity depending on which list item is clicked.

  • Changes to AndroidManifest.xml

  • We introduce a MenuList activity in the AndroidManifest.xml and make is the launcher.

  • One shouldn’t forget to change all other activity action name to class paths and the category to Launcher.

  • Following screenshots show the running of the application.

 

 

MenuList.java

 

package com.example.helloandroid;

 

import android.app.ListActivity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.ArrayAdapter;

import android.widget.ListView;

 

public class MenuList extends ListActivity{

String classes[]={"Example","MainActivity","Password","Not Present”,”Not Present”, ”Not Present”, ”Not Present”};

protected void onCreate(Bundle savedInstanceState) {

// TODO Auto-generated method stub

super.onCreate(savedInstanceState);

setListAdapter(new ArrayAdapter<String>(MenuList.this,

android.R.layout.simple_list_item_1,classes));

}

 

@Override

protected void onListItemClick(ListView l, View v, int position, long id) {

// TODO Auto-generated method stub

super.onListItemClick(l, v, position, id);

try{

Intent in =new Intent("com.example.helloandroid."+classes[position].toUpperCase());

startActivity(in);

}catch(Exception e){

e.printStackTrace();

}

}

}

 

 

Pr.Pg border                                              Next Pg