Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to create List in Android Applications with Array Adapter

In this tutorial we will learn how to manage lists in your Android application. We will see also how to create and use ListView, Manage list items through ListAdapter, Create ListActivity having default view as ListView.

Introduction

Lists are essential component in many Android applications. The main points that will be learnt are:

  • Create and use ListView
  • Manage list items through ListAdapter
  • Create ListActivity having default view as ListView
  • Create Complex List item composed of custom GUI components, like an EditBox with Button for example, or any other combination by overriding the ArrayAdapter class

A list view is a kind of Android views that can be added to any xml layout to include list items:

Listing 1: ListView

    <ListView
        android : id = "@ +id/listView "
        android : layout_width = " match_parent "
        android : layout_height = " wrap_content " 
   android : layout_centerHorizontal = " true">
    </ ListView>

The list view resource defined above is associated with ListView class which manages all GUI resources of the view, like viewing list items . In your activity you get a reference to the list view as follows:

ListView listViewHandle =  ( ListView )  findViewById ( R . id . listView )  ;

Once this handle is obtained, you must set its adapter as in ý3 . The adapter, as will be learnt, is mandatory to reflect the changes that happens to the underlying list structure to the GUI view . For example, if you manage an array list, and you wish to add an item at certain position, so you want this item to be viewed at that position on the GUI . In this case, you let the adapter do this job for you . Also, you can tell the adapter how this item should be viewed on the GUI as will appear next .

ArrayAdapter

Each list view has an associated data structure, like Array, ArrayList,…etc, which holds the data of its items. To link the data structure to the GUI list view, the class BaseAdapter is used, of which ArrayAdapter is inherited. This kind of classes is used to adapt the view of each list item to the data of the underlying data structure (ArrayList for example) without much effort from the programmer, by just overriding the getView method as will be shown later .

Listing 2: Creating the data structure of the list:

ArrayList<String> itemsList = new ArrayList<String> (  )  ;
            itemsList . add ( "Item 1" )  ;
            itemsList . add ( "Item 2" )  ;

Listing 3: Creating a new adapter that manages this data structure:

ArrayAdapter<String> adapter = new ArrayAdapter<String> ( this, android . R . layout . simple_list_item_1, itemsList )  ;

Listing 4: Associating this adapter to your list view to manager list items:

listViewHandle . setAdapter ( adapter )  ;

Complex List Item

By creating an adapter directly from ArrayAdapter class, you associate the view of each list item to single text representing the items in your structure. If your list is composed of complicated item view; like for example a (text box + button + edit box) , then you need to extend the class ArrayAdapter, and override its method getView, which is called each time the activity is refreshed, and every time the method adapter . notifyDataSetChanged ( ) is called . In such case, you define the layout of your custom item in xml file, and inflate it inside getView .

First you need to override the constructor of the adapter to store the underlying data structure, plus any other needed data that will be used later with getVie.

Listing 5: Exampple of LayoutInflater that will be used to inflate the custom item list :

public class NewListAdapter extends ArrayAdapter <Day> 
{
	LayoutInflater mInflater ;	
      private List<Day> mItems ;
	

	public NewListAdapter  ( Context context , List<Day> items, LayputInflater inflater )  
	{
		super ( context, -1, items )  ;
		this . mItems = items ;
            this . mInflater = inflater ;
		
	}

Where you have an array list of items, each of type “Day”, which is a special class composed of “mProgress”, and “mDate”. Notice how the constructor is passed the list of items to be managed, and a reference to the LayoutInflater that will be used later to inflate the custom list items. The button does nothing in this example, it is just added for the sake of demonstration.

Suppose that your custom list item is managed in some file called custom_list_item.xml

Listing 6: xml composed of text view, plus button, and a progress bar, all representing single list item.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/dateCell"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />
    
    <SeekBar xmlns:android=<http://schemas.android.com/apk/res/android>
android:id="@+id/progressBar"
      android:layout_width="match_parent"
      android:layout_height="match_parent" >
    

    </SeekBar>

</LinearLayout>

Listing 7: Then you override getView as follows () :

	@ Override
	public View getView ( int position, View convertView, ViewGroup parent )  
	{
			// Inflate the custom view
			convertView =   mInflater .  inflate ( R . layout .  custom_list_item, null )  ;

			final Day currDay =  ( Day ) mItems  .  get ( position )  ;
			
            // Set the progress bar
			 (  ( ProgressBar )  convertView  .  findViewById ( R .  id . progressBar )  )  . setProgress (  ( int )  currDay . getProgress (  )  ) 
			
			// Set the Date text		
			 (  ( TextView )  convertView  .  findViewById ( R  .  id  . dateCell )  )  .  setText ( currDay . getDateAsString (  )  )  ;
			
			return convertView ;
}

Notice how the custom view is inflated at the first line of getView using the inflater that was passed to the constructor, and then the item corresponding to the current positions is obtained from the underlying list (the second line of getView ) , and then the items of the custom view are filled one by one, finally the final view is returned, which is viewed in the “position” of the list view .

In your base activity, whenever you modify your list, you must call adapter. notifyDataSetChanged ( ) for your change to have effect on the actual list view, where all positions are looped over with getView called with the different positions in the list to refresh it, otherwise, the new effect will not take place until the activity is refreshed. The complex items look like Figure 1.

Custom List Item: Text + Button + Progress Bar

Figure 1: Custom List Item: Text + Button + Progress Bar

With each call of the adapter. notifyDataSetChanged ( ) all positions of the underlying data structure are looped over, and each time getView is called, where the corresponding item of the list is obtained, and then the data of each GUI component is obtained from the item of the list . In the above example, the date field of the currDay is used to fill the text view, and the progress filed is used to set the progress of the progress bar.

ListActivity and ListView

Some applications are nothing more than a ListView . For such apps, it is recommended to use the ListActivity class and extend it. This special type of activities has a default layout formed of ListView that fills the whole layout. This is a special class, to use it you must extend the ListActivity base class:

public class TestListViewActivity extends ListActivity

By doing this you create an activity with the ListView filling completely its layout, hence you need not inflate any . xml layout . However, you can also create custom ListView by creating your own xml layout for each list item and inflate it, see ý4 .

To access the list view associated with the ListActivity you just need to call getListView member method of the class . Within ListActivity, you will need to set the list adapter associated with it .

Listing 8: This is done in the onCreate method as follows:

 @ Override
    public void onCreate  ( Bundle savedInstanceState )  
    {
        super . onCreate  ( savedInstanceState )  ;
        ArrayList <String> itemsList = new ArrayList <String> (  )  ;
        itemsList  .  add ( "Item 1" )  ;
        itemsList  .  add ( "Item 2" )  ;
        itemsList  .  add ( "Hello" )  ;
        itemsList  .  add ( "Item 3" )  ;
  ArrayAdapter <String> adapter = new ArrayAdapter <String> (  this,    android . R . layout . simple_list_item_1, itemsList )  ;
        getListView (  )   .  setAdapter  ( adapter )  ;
}

When you run this activity you get the view in Figure 2

ListActivity with full ListView

Figure 2: ListActivity with full ListView

Also, you can override any method related to handling item events, like for example if you want to view the text of the clicked list item (see Figure 3) :

Listing 9: Example to display view of the text of the clicked list item

	@ Override
protected void onListItemClick  ( ListView l, View v, int position, long id ) 
	{
		TextView textView =  ( TextView ) v  .  findViewById (  ( int ) id )  ;
		
		//TextView textView =  ( TextView )  v ;// working
Toast . makeText ( this, textView .  getText (  ) , Toast .  LENGTH_SHORT )  . show (  )  ; // working
	}
Item 2 is clicked

Figure 3: Item 2 is clicked

Conclusion

In this tutorial we learned:

  • How to create ListView in Android application
  • How to create ListActivity
  • How to override ArrayAdapter for custom list view


Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login