Presentation is loading. Please wait.

Presentation is loading. Please wait.

ListView.

Similar presentations


Presentation on theme: "ListView."— Presentation transcript:

1 ListView

2 What is a list view? A ViewGroup that displays scrollable items.

3 3 Parts of a ListView The ListView itself List items
aka 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

4 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

5 Where does the data come from?
ListViews receive data via Adapters. The Adapter behaves as the middleman between the data source and the ListView.

6 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.

7 How an Adapter Works Bill and Ted… Bill and Ted’s Excellent… Adapter
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

8 Data source for Adapters
Arrays Content Provider Used to get Calendar and Contact info from phone. Database Cursor

9 Types of Adapters ArrayAdapter SimpleCursorAdapter 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

10 Hello World ListView Example

11 Layout Resource <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android=" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <ListView android:layout_height="wrap_content" > </ListView> </LinearLayout> What is missing from this XML layout that the screen shot is showing?

12 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 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); }

13 Code Inflate the layout for the Activity.
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 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); } Inflate the layout for the Activity.

14 Code Extract the ListView from the layout Create data source for list
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 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); } Extract the ListView from the layout Create data source for list

15 Code Create the Adapter
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 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); } Create the Adapter

16 Creating Adapter: Parameter 1
// First paramenter - Context ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values); 1

17 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, android.R.id.text1, values); 2

18 Creating Adapter: Parameter 3
// First paramenter - Context // Second parameter - Layout for the list item or row // Third parameter - ID of the TextView to which the data is written ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, values); 3

19 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

20 Code Set adapter to ListView to bind data
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 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

21 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);

22 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);

23 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!

24 android.R.layout.simple_list_item_1
<TextView xmlns:android=" 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">

25 Android Platform Built-in Layouts

26 View the XML for Built-in Layouts

27 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

28 Resource ID for each Layouts
The resource ID for the TextView inside each built in Android layout is the same:

29 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);

30 ListView Example Result

31 AdapterView ListView derives from AdapterView
AdapterViews are Views that use Adapters. There are several other AdapterView subclasses that behave much like ListView.

32 Subclasses of AdapterView
AdapterViewFlipper GridView Spinner Gallery StackView ExpandableListView

33 Back to ListView How to add event handling?

34 Adding Click Handler To react to clicks in the list, set an onItemClickListener on your ListView.

35 onItemClickListener Example
// Assign adapter to ListView listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG) .show(); } });

36 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.

37 onItemClickListener Example
// Assign adapter to ListView listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG) .show(); } });

38 OnItemClickListener Result

39 Would you like some Toast?

40 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. The Toast displays on top of the current activity, but the activity is still visible and interactive.

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

42 Toast Example Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG) .show(); 2 Context String message to print

43 Toast Example Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG) .show(); 3 Context String message to print Duration to display Toast

44 Toast Example Toast.makeText(getApplicationContext(), "Click ListItem Number " + position, Toast.LENGTH_LONG) .show(); 4 Context String message to print Duration to display Toast Method to make the Toast show itself

45 Specify Toast Duration
The Toast Object has two predefined durations. LENGTH_LONG ~3.5 seconds LENGTH_SHORT ~2 seconds You can’t specify a custom duration.

46 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.

47 Toast Location example
toast.setGravity(Gravity.TOP|Gravity.LEFT, 0, 0);

48 Modifying Your List How do I add more items?
How can I add a set of items? How do I clear all items?

49 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

50 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.

51 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.

52 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.

53 ListActivity

54 ListActivity Useful when your Activity only supports a single list.
ListActivity was designed to simplify the handling of ListViews.

55 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.

56 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

57 ListActivity helper methods
ListActivity provides helper methods for List Item Click events Setting the ListView’s adapter

58 ListActivity click handling
When using a ListActivity, you don’t need to implement an onItemClickListener(). ListActivity already implements one for you. ListActivity’s onListItemClick() to handle list click events.

59 Setting the ListView’s adapter with ListActivity
ListActivity provides the setListAdapter() method. Internally calls setAdapter() on the ListView for the ListActivity.

60 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); } Nothing fancy happening here, just creating a data source (Array), creating an Adapter and passing it to the ListActivity’s ListView. No need to call setContentView() because the ListActivity does that for us.

61 ListView Recycling

62 Beginner’s initial impression of ListView
The ListView probably creates a view for each list item and only displays the item currently on screen. This is an incorrect assumption!

63 Bill and Ted’s Excellent…
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master", "Land Before Time", "TMNT", "Weird Science", "Goonies", "Total Recall", "Howard the duck", "Kindgergarden Cop", "Bloodsport", "Universal Soldier", "Ernest scared stupid", "Dumb and Dumber", "Breakfast Club" }; Bill and Ted’s Excellent… Teen Wolf Honey I shrunk… ListView Texas Chainsaw Mas… ListItem Pupper Master Land Before Time TMNT Weird Science Goonies

64 ListView recycles its items
To cut down on View Objects, a ListView will only allocate enough Item Views to “roughly” fill the size of a ListView. When a Item gets scrolled off the ListView, its view will be reused by a new Item that is scrolling on to the ListView.

65 Bill and Ted’s Excellent…
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master", "Land Before Time", "TMNT", "Weird Science", "Goonies", "Total Recall", "Howard the duck", "Kindgergarden Cop", "Bloodsport", "Universal Soldier", "Ernest scared stupid", "Dumb and Dumber", "Breakfast Club" }; Bill and Ted’s Excellent… Teen Wolf Honey I shrunk… Texas Chainsaw Mas… Pupper Master Land Before Time

66 ListView Recyling Automatically taken care of by the ListView when using a standard ArrayAdapter. However, if you implement your own Adapter you’ll have to do a little work.

67 How Adapters work internally

68 Quick look at ArrayAdapter.java
Lets look at how the ArrayAdapter class does the following: Creates list item Views Recycles list item Views

69 How an Adapter Works Adapter
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master" } Adapter getView(int position, View convertView, ViewGroup parent) 1 1. Position of the list item we want. ListView

70 How an Adapter Works Adapter 2
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master" } Adapter 2 getView(int position, View convertView, ViewGroup parent) 1. If the ListView has any recycled Views it will send one of these recycled Views for the Adapter to use; else, it will send null. ListView

71 How an Adapter Works Adapter
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master" } Adapter getView(int position, View convertView, ViewGroup parent) 3 3. The parent of the list item; in this case, the ListView. ListView

72 Getting First Item for List
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master" } Adapter getView(0, null, this) ListView

73 How an Adapter Works Adapter Bill and Ted’s Excellent…
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master" } Adapter Bill and Ted’s Excellent… getView(0, null, this) ListView

74 How did the Adapter generate the list item View?

75 Code taken from ArrayAdapter.java
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; Code taken from ArrayAdapter.java

76 The layout resource we passed into the Adapter’s constructor,
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; The layout resource we passed into the Adapter’s constructor, Aka the layout we requested to use for each list item. Code taken from ArrayAdapter.java

77 If convertView is null, we need to create
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; If convertView is null, we need to create a new View. Inflate the layout resource to do this. Code taken from ArrayAdapter.java

78 If convertView isn’t null, we need can reuse the recyled view.
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; If convertView isn’t null, we need can reuse the recyled view. Code taken from ArrayAdapter.java

79 Find the TextView within the list item layout.
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; Find the TextView within the list item layout. Code taken from ArrayAdapter.java

80 Fetch the data (stored in the Adapter) that is
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; Fetch the data (stored in the Adapter) that is associated with this list item position. Code taken from ArrayAdapter.java

81 ArrayAdapter only sets the text for the TextView
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; ArrayAdapter only sets the text for the TextView included in the list item layout resource. So extract the String from Object and set the TextView’s text. Code taken from ArrayAdapter.java

82 How an Adapter Works Adapter Bill and Ted’s Excellent…
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master" } Adapter Bill and Ted’s Excellent… getView(0, null, this) ListView

83 Code taken from ArrayAdapter.java
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; null ListView true Code taken from ArrayAdapter.java

84 Code taken from ArrayAdapter.java
public View getView(int position, View convertView, ViewGroup parent) { return createViewFromResource(position, convertView, parent, mResource); } private View createViewFromResource(int position, View convertView, ViewGroup parent, int resource) { View view; TextView text; if (convertView == null) { view = mInflater.inflate(resource, parent, false); } else { view = convertView; try { if (mFieldId == 0) { // If no custom field is assigned, assume the whole resource is a TextView text = (TextView) view; // Otherwise, find the TextView field within the layout text = (TextView) view.findViewById(mFieldId); } catch (ClassCastException e) { Log.e("ArrayAdapter", "You must supply a resource ID for a TextView"); throw new IllegalStateException( "ArrayAdapter requires the resource ID to be a TextView", e); T item = getItem(position); if (item instanceof CharSequence) { text.setText((CharSequence)item); text.setText(item.toString()); return view; null ListView Bill & Ted’s… Code taken from ArrayAdapter.java

85 How an Adapter Works Adapter Bill and Ted’s Excellent…
Array<String> mMovies = { "Bill and Ted's Excellent Adventures", "Teen Wolf", "Honey I shrunk the kids", "Texas Chainsaw Massacre", "Puppet Master" } Adapter Bill and Ted’s Excellent… getView(0, null, this) ListView

86 Implementing your own adaper

87 Custom Adapter The default look and feel of the Android ListView is not very attractive. Also, remember the default action of an ArrayAdapter is to call the toString() method on the data object it contains. This means your list will change the text on the list item and nothing else.

88 Getting creative with Custom Adapters
With Custom Adapters, you can use your own layout to make lists more interesting. You can make the list items look any way you want. You can make the list item have more data than just simple text.

89 Steps for create a custom adapter
Extend an existing Adapter class Define a constructor @Override the Adapter’s getView() method. Use this to inflate custom list items Use this to populate the item with more data than just what comes from toString().

90 Extend an existing Adapter
Create a class that extends BaseAdapter ArrayAdapter SimpleCursorAdapter You’ll want to extend an existing adapter because they provide quite a bit of functionality that we don’t want to rewrite ourselves.

91 Custom Adapter Example
public class MoviePosterAdapter extends ArrayAdapter<String> { }

92 Define a constructor Use the constructor for the following:
Specify the layout to be used by Adapter for list items Get access/save a reference to the adapter’s data source Initialize any startup logic for your adapter

93 Custom Adapter Constructor
public class MoviePosterAdapter extends ArrayAdapter<String> { public MoviePosterAdapter(Context context) { super(context, R.layout.movie_list_item, R.id.text, context.getResources().getStringArray(R.array.movie_list)); } 1 1. Implementing a constructor that takes only a context and forces it to use a layout defined in my application’s resources.

94 Custom Adapter Constructor
public class MoviePosterAdapter extends ArrayAdapter<String> { public MoviePosterAdapter(Context context) { super(context, R.layout.movie_list_item, R.id.text, context.getResources().getStringArray(R.array.movie_list)); } 2 2. Make the Adapter use the movie_list_item layout.

95 Custom Adapter Constructor
public class MoviePosterAdapter extends ArrayAdapter<String> { public MoviePosterAdapter(Context context) { super(context, R.layout.movie_list_item, R.id.text, context.getResources().getStringArray(R.array.movie_list)); } 3 3. Point the Adapter to use the TextView, defined in the movie_list_item layout, whose id is equal to R.id.text

96 Custom Adapter Constructor
public class MoviePosterAdapter extends ArrayAdapter<String> { public MoviePosterAdapter(Context context) { super(context, R.layout.movie_list_item, R.id.text, context.getResources().getStringArray(R.array.movie_list)); } 4 4. Pass the data used by the adapter into the super.

97 Using the Custom Adapter on a ListView
public class MyListWithCustomAdapterActivity extends ListActivity public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); MoviePosterAdapter mpAdapter = new MoviePosterAdapter(this); setListAdapter(mpAdapter); } Using this constructor will setup the Adapter using the Constructor method defined in my custom adapter.

98 Custom Adapter Example Result

99 Must @Override getView()
The ArrayAdapter class only knows how to update each list item’s text. If your list item uses any other data, your getView() needs to implement logic to properly set up the list item to display the necessary data.

100 Basic getView() implementation
public class MoviePosterAdapter extends ArrayAdapter<String> { public MoviePosterAdapter(Context context) { super(context, R.layout.movie_list_item, R.id.text, context.getResources(). getStringArray(R.array.movie_list)); public View getView(int position, View convertView, ViewGroup parent) { View listItem = super.getView(position, convertView, parent); return listItem;

101 MoviePosterAdapter Example
Implement the Adapter to keep track of which list items are checked. The Adapter needs to keep a reference to some object that keeps track of this. The getView() needs to use that object and determine if it should check an item or not.

102 Add a HashMap to keep track of checked items
public class MoviePosterAdapter extends ArrayAdapter<String> { private HashMap<Integer, Boolean> mMovieHash = new HashMap<Integer, Boolean>(); public MoviePosterAdapter(Context context) { super(context, R.layout.movie_list_item, R.id.text, context.getResources().getStringArray(R.array.movie_list)); mMovieHash.put(1, true); public View getView(int position, View convertView, ViewGroup parent) { View listItem = super.getView(position, convertView, parent); CheckBox box = (CheckBox) listItem.findViewById(R.id.checkbox); boolean contains = mMovieHash.containsKey(position); if (contains && mMovieHash.get(position)) { box.setChecked(true); } else { box.setChecked(false); return listItem;

103 ListView with MoviePosterAdapter


Download ppt "ListView."

Similar presentations


Ads by Google