You are on page 1of 57

ListView

T.Heba AL.Marwai
What is a list view?
• A ViewGroup that displays scrollable items.
3 Parts of a ListView
• The ListView itself
– A ViewGroup
• List items
– Each row/item in the list. Each item is a layout
consisting of a View or ViewGroup.
• Data for each item
ListItem
• Since the ListItem can be a ViewGroup, we
have the power to display very simple or
extremely complex layouts for each item.
– A TextView
– A TextView and ImageView
– A TextView and CheckBox
– A TextView and Button
– A TextView, ImageView, CheckBox, Button, and
RatingBar, etc
Where does the data come from?
• ListViews receive data via Adapters.

• The Adapter behaves as the middleman


between the data source and the ListView.
The job of an Adapter
• The Adapter fetches data from the source.

• Creates the layout that represents each list item.

• Takes the data fetched from the source places it


into the list item layout.

• Returns a list item to the ListView.


How an Adapter Works
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen
Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre",
"Puppet Master" }
Bill and Ted…

Bill and Ted’s


Excellent…
Adapter
Teen Wolf

Honey I shrunk…

Texas Chainsaw Mas…

Pupper Master

ListView
Data source for Adapters
1. Arrays

2. Content Provider
– Used to get Calendar and Contact info from
phone.

3. Database Cursor
Types of Adapters
• ArrayAdapter
– Works with Arrays
– Can handle any Java Object as input
– Uses the .toString() method of the JavaObject to
obtain text for list item.

• SimpleCursorAdapter
– Works with a Content Provider and Database
Cursor
Hello World ListView Example
Layout Resource
<?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" >

<ListView
android:id="@+id/mylist"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>

</LinearLayout>
Code
package com.example.lecture2;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListLecture extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_lecture);

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


String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };

// First parameter - Context


// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);

// Assign adapter to ListView


listView.setAdapter(adapter);
}
}
Code
package com.example.lecture2;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
Inflate the layout
public class ListLecture extends Activity {
for the Activity.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_lecture);

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


String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };

// First paramenter - Context


// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);

// Assign adapter to ListView


listView.setAdapter(adapter);
}
}
Code
package com.example.lecture2;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListLecture extends Activity {


Extract the ListView from the layout
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_lecture);

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


String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };

// First paramenter - Context


Create data source for list // Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);

// Assign adapter to ListView


listView.setAdapter(adapter);
}
}
Code
package com.example.lecture2;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListLecture extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_lecture);

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


String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };

Create the Adapter // First parameter - Context


// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);

// Assign adapter to ListView


listView.setAdapter(adapter);
}
}
Creating Adapter: Parameter 1
// First paramenter - Context

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1, values);
Creating Adapter: Parameter 2
// First paramenter - Context
// Second parameter - Layout for the list item or row

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1,values);

2
Creating Adapter: Parameter 3
// First paramenter - Context
// Second parameter - Layout for the list item or row

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1,
android.R.id.text1, values);

3
Creating Adapter: Parameter 4
// First paramenter - Context
// Second parameter - Layout for the list item or row
// Third parameter - ID of the TextView to which the data is
written
// Forth - the Array of data

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1,
android.R.id.text1, values);

4
Code
package com.example.lecture2;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListLecture extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_lecture);

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


String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };

// First paramenter - Context


// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);

// Assign adapter to ListView


listView.setAdapter(adapter);
} Set adapter to ListView to bind data
}
Mystery Layout and ID???
// First paramenter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is
written
// Forth - the Array of data

ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,


android.R.layout.simple_list_item_1,
android.R.id.text1, values);
Mystery Layout and ID???
// First paramenter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is
written
// Forth - the Array of data

//Accessing resource from our project


setContentView(R.layout.list_lecture);

//Accessing resource from Android Platform (Accessible to all apps)


ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1, values);
Layouts provided by Android Platform
• The Android Platform provides built-in XML
layouts.

• These built-in layouts are accessible to all


applications.

• Makes it even easier to use common layouts!


android.R.layout.simple_list_item_1
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:gravity="center_vertical"
android:paddingLeft="6dip"
android:minHeight="?android:attr/listPreferredItemHeight">
Android Platform Built-in Layouts
• http://developer.android.com/reference/andr
oid/R.layout.html
View the XML for Built-in Layouts
• http://www.netmite.com/android/mydroid/fr
ameworks/base/core/res/res/layout/
Built-in Layouts for ListViews
• simple_list_item_1.xml
• simple_list_item_2.xml
• simple_list_item_checked.xml
• simple_list_item_multiple_choice.xml
• simple_list_item_single_choice.xml
Resource ID for each Layouts
• The resource ID for the TextView inside each
built in Android layout is the same:

android:id="@android:id/text1"
Not so mysterious Layout and ID???
// First paramenter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is
written
// Forth - the Array of data

//Accessing resource from our project


setContentView(R.layout.list_lecture);

//Accessing resource from Android Platform (Accessible to all apps)


ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,
android.R.id.text1, values);
ListView Example Result
Back to ListView
• How to add event handling?
Adding Click Handler
• To react to clicks in the list, set an
onItemClickListener on your ListView.
onItemClickListener Example
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
onItemClick Parameters

onItemClick(AdapterView<?> parent, View view, int position, long id)

parent The AdapterView where the click


happened.

view The view within the AdapterView that


was clicked (this will be a view provided
by the adapter)

position The position of the view in the adapter.

id The row id of the item that was clicked.


onItemClickListener Example
// Assign adapter to ListView
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
OnItemClickListener Result
Toast Message
• A Toast provides simple feedback about an
operation in a small popup.

• The Toast only fills enough space to wrap the


text of the message.
Toast Example

Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();

1. Context
Toast Example

Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
2

1. Context
2. String message to print
Toast Example

Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
3

1. Context
2. String message to print
3. Duration to display Toast
Toast Example

Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();

1. Context
2. String message to print
3. Duration to display Toast
4. Method to make the Toast show itself
Specify Toast Duration
• The Toast Object has two predefined
durations.
1. LENGTH_LONG ~3.5 seconds

2. LENGTH_SHORT ~2 seconds
Specify Location of Toasts
• A standard toast notification appears near the
bottom of the screen, centered horizontally.

• You can change this position with


the setGravity(int, int, int) method.

• This accepts three parameters:


a Gravity constant, an x-position offset, and a
y-position offset.
Toast Location example

toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);
Modifying Your List
• How do I add more items?
• How can I add a set of items?
• How do I clear all items?
ArrayAdapter Helper Methods
• add(T Object) – Adds the specified object to the end of the array.

• addAll(T… items) – Adds the specified items at the end of the


array.

• clear() – Remove all elements from the list


ArrayAdapter Helper Methods
• notifyDataSetChanged() – notification that the underlying
data has been changed and that the View should refresh itself.

• remove(T Object) – Removes the specified object from the


array.
ArrayAdapter Helper Methods
• getItem(int position) – gets Object at specified position in
adapter.

• getPosition(T item) – Returns the position of the specified item


in the array.
ArrayAdapter Abilities
• Filtering – filter data by a certain constraint
– Only show data that begins with the letter “S.”

• Sorting – sort the contents of the adapter


using a specified comparator.
– Sort by alpha A-Z, alpha Z-A, etc.
ListActivity
ListActivity
• Useful when your Activity only supports a
single list.

• ListActivity was designed to simplify the


handling of ListViews.
Standard ListActivity
• ListActivity has a default layout that consists
of a single full-screen list in the center of the
screen.

• ListActivity does not require that you assign it


a layout resource via setContentView().
ListActivity handles that for you.
Custom ListActivity
• If you want to include more views than just a
ListView in your Activity, you may call
setContentView() yourself with your own
layout.

• In this case, your layout MUST contain a


ListView with the android:id attribute set to
@android:id/list
ListActivity helper methods
• ListActivity provides helper methods for
– List Item Click events
– Setting the ListView’s adapter
ListActivity click handling
• When using a ListActivity, you don’t need to
implement an onItemClickListener().

• ListActivity already implements one for you.

• Simply @Override ListActivity’s


onListItemClick() to handle list click events.
Setting the ListView’s adapter with
ListActivity
• ListActivity provides the setListAdapter()
method.

• Internally calls setAdapter() on the ListView


for the ListActivity.
ListActivity Example
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;

public class MyListActivity extends ListActivity {


public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] values = new String[] { "Android", "iPhone",
"WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
}
}

You might also like