10
Instructor’s Notes Unit 7 - ListViews Page 1 of 10 Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text References Overview Pages ListView Pages ArrayAdaper Pages Filling a ListView Pages Sensing Click Pages Selected Item Info Pages Configuring a Spinner Pages AutoCompleteTextView Pages Custom List Item View Pages Overview One of the most commonly used Views is the ListView Like a Windows ListBox, the ListView provides a scrollable list of items that can be clicked to select them ListViews can also allow the user to select multiple items. Use for: lists of emails, lists of contacts, call log, text message threads, settings lists, etc. Android also provides a Spinner object which is more like a ComboBox. The structure of a Spinner is very close to a ListView; but its screen appearance is different AutoCompleteTextView also uses a list to generate a list of choices that narrows as the user types in a TextView GridView provides a table-like layout where the list fills both rows and columns (not covered in these notes). Similar to the home screen icon layout, but displaying text instead of images Gallery provides a table-like layout as well, but is typically used to display icons or thumbnails. (not covered in these notes)

Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

  • Upload
    lamdang

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 1 of 10

Introductory Mobile App Development

152-160

Unit 7 - ListViews

Notes Activity

Quick Links & Text References

Overview Pages

ListView Pages

ArrayAdaper Pages

Filling a ListView Pages

Sensing Click Pages

Selected Item Info Pages

Configuring a Spinner Pages

AutoCompleteTextView Pages

Custom List Item View Pages

Overview

One of the most commonly used Views is the ListView

Like a Windows ListBox, the ListView provides a

scrollable list of items that can be clicked to select

them

ListViews can also allow the user to select multiple

items.

Use for: lists of emails, lists of contacts, call log, text

message threads, settings lists, etc.

Android also provides a Spinner object which is more like

a ComboBox.

The structure of a Spinner is very close to a

ListView; but its screen appearance is different

AutoCompleteTextView also uses a list to generate a list

of choices that narrows as the user types in a TextView

GridView provides a table-like layout where the list fills

both rows and columns (not covered in these notes).

Similar to the home screen icon layout, but

displaying text instead of images

Gallery provides a table-like layout as well, but is

typically used to display icons or thumbnails. (not

covered in these notes)

Page 2: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 2 of 10

Notes Activity

The Android ArrayAdapter is a special class used to

simplify the filling of a list.

We will be filling an array of strings and then

converting that array to an ArrayAdapter and linking

it to our list.

ListViews are so common, Android provides a

ListActivity class (subclass of Activity) to simplify list

management in Java.

ListActivity is particularly useful if the only View in

the layout is a ListView.

ListView

The ListView is defined in a layout file like all other

views.

Typically, you define the ListView’s height and width

(usually match_parent) and provide it an ID.

ID required; list can only be filled in Java

The android:drawSelectorOnTop attribute (Boolean) is

used to designate whether a drop-down arrow should be

displayed (typically true for Spinners)

The android:choiceMode attribute designates whether

the user can select a single or multiple items from the list

(single by default, use multipleChoice in XML to

designate multiple selections allowed.

When set to multiple, each list item includes a check

box to designate whether it is selected or not.

ListViews automatically include the ability to scroll

through the list if the list is longer than the space

provided.

Generate (Linear) layout

with TextView at top and

a ListView

Define and fill a class-

level ArrayList of student

names

Page 3: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 3 of 10

Notes Activity

ArrayAdapter

Before defining an ArrayAdapter, define and fill either an

array or an ArrayList that contains the items you want

added to the list.

As mentioned in the overview, Android provides the

ArrayAdapter class to simplify filling a ListView

Defining an ArrayAdapter

ArrayAdapter adt = new ArrayAdapter<String> (this, android.R.layout.simple_list_item_1,

arrayName);

adt is simply a variable name

<String> designates the type of the items in the

array (adjust as needed for your array)

If your array contains a class, be sure to define a

custom ToString method to designate which

field (or combination of fields) should be

displayed in the list.

this refers to the current activity.

android.R.layout.simple_list_time_1 is a

predefined Android constant that defines a simple

layout for simple lists

You can define your own custom layout for each

item in the list (not covered in these notes)

android.R.layout.

simple_list_item_multiple_choice is also

available

If you designate the ListView as single but apply

the multiple layout, you’ll get single select with

check boxes.

arrayName is the name of the array (or ArrayList)

containing the items to be added to the list.

Often, the ArrayAdapter variable (adt) is never defined.

The new ArrayAdapter statement is embedded in the

setAdapter command described below

Define an ArrayAdapter

for single select list

Page 4: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 4 of 10

Notes Activity

Filling a ListView

Using a Regular Activity

Give the ListView an ID

predefined name described below is only used

by ListActivity

Define array or ArrayList to hold the items to be

added to the list

Define an ArrayAdapter and configure it to use the

array

Optional: Can be combined with the next

command

lv.setAdapter(adt);

adt is the ArrayAdapter variable

Can be replaced with new ArrayAdapter(~~)

setAdapter

Test

Convert to multi-select

(layout and code)

Test

Select multiple.

Refreshing a ListView

adt.notifyDataSetChanged();

adt must be a class-level variable to retain its

connection to the ListView and to allow this

command to be used in numerous locations.

Alternative: set the adapter again

Code btnAdd to add new

name to ArrayList (at 0?)

and notify, clear (only if

not blank)

Sensing When an Item Is Clicked

Define a listener for the ListView

lv.setOnItemClickListener(this);

or (anonymous function)

lv.setOnItemCLickListener(

new onItemClickListener() {});

Right-click and implement the required methods

Code onItemClick

Define

onItemClickListener

Toast position and id

Page 5: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 5 of 10

Notes Activity

Getting Information About a Selected Item

The first parameter (I rename it lv) is a pointer to the

ListView

The second parameter (view) contains the text of the

selected item

You can extract it using getText String sel =

((TextView)view).getText().toString();

Note need to convert generic View to a TextView

You can also get the text using the first parameter: lv.getItemAtPosition(position).toString()

The third parameter (position) contains the index of the

selected item.

This is usually used to refer back to the original

array/ArrayList and extract data from there.

Probably more efficient assuming the array/ArrayList

is in sync with the items in the ListView.

The fourth parameter (id) seems to always match position

(at least for our simple applications)

Get text, add to Toast

Get from parent,

Show in Toast

Get from ArrayList

Show in Toast

You can also use setText on the second parameter to

change the item in the list

TextView row = (TextView) view;

row.setText("new text");

Be sure to change the text in the original array too

Probably a better idea to change the ArrayList

element and notify change to array adapter

Try it.

You can get/set the checked status of a multi-select list

item

The first parameter points to the parent item( the

ListView)

Assume arg0 renamed parent

Also convert to a ListView in regular Activity

ListView p = (ListView) parent;

p.setItemChecked(position,

true|false);

The visible check box items in the list automatically

toggle when you click the item or the check box.

Optional: modify code

selection to check next

item

Getting the checked status of an item is also simple:

p.isItemChecked(position)

Toast which items are

selected.

(LAB)

Page 6: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 6 of 10

Notes Activity

Configuring a Spinner

A Spinner is Android’s version of the drop-down combo

box.

The list that appears when you click the arrow is defined

using an ArrayAdapter like the ListView

Add Spinner to layout

ID

Height and width

In Java

Create Spinner pointer variable

Define array or ArrayList(needed to fill

ArrayAdapter)

Fill array/ArrayList

Define onItemSelectedListener

Optional:

rename arguments: parent, v, position, id

Note a onNothingSelected handler is also

required.

Add a Spinner to display

the months of the year.

(Non-LA version of

program)

In the listener simply

Toast the selected position

and/or text

Define the ArrayAdapter ArrayAdapter<String> adapter =

new ArrayAdapter<String>(this,

android.R.layout.simple_spinner_item,

arrayName);

adapter is simply a variable name

android…simple_spinner_item is a built-in,

simple layout for one Spinner list item

▪ You could define your own layout

arrayName is the name of the array or ArrayList

For Spinner objects, you also have to define a drop down

view adapter.setDropDownViewResource(

android.R.layout.simple_spinner_dropdown_item);

adapter is the ArrayAdapter defined above

android…dropdown_item is another built-in, simple

layout view.

Note the only difference between this layout and the

one above is the word dropdown.

Page 7: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 7 of 10

Notes Activity

Finally, set the Spinner adapter to the ArrayAdapter

you defined. mySpinner.setAdapter(adapter);

NOTE: item 0 in the list is automatically selected

when your application starts and the event handler

fires

Configuring an AutoCompleteTextView

Android also includes an AutoCompleteTextView

All the features of a TextView

When user starts typing (after a designated number of

characters), a list of potential choices (those that start

with the letters the user typed) appears and can be

selected

If the letters are not on the list, the user may

simply continue typing.

Also uses an ArrayAdapter to define the list.

Add AutoCompleteTextView to the layout

ID

Width, height

android:completionThreshold="3"

Number of characters user must enter before list

appears

Default is 2

Note: the AutoCompleteTextView width must be

wide enough to show the widest anticipated item (not

wrap_content).

Add an

AutoCompleteTextView

to provide the months

In Java

Create AutoCompleteTextView pointer variable

Define array or ArrayList(needed to fill

ArrayAdapter)

Fill array/ArrayList

Define addTextChangedListener (optional) tvMonth.addTextChangedListener(new TextWatcher() {

Page 8: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 8 of 10

Notes Activity

In onTextChanged, add code as needed

Define the ArrayAdapter ArrayAdapter<String> adapter =

new ArrayAdapter<String>(this,

android.R.layout.simple_dropdown_item_1line,

arrayName);

adapter is simply a variable name

android…simple_dropdown_item_1line is a

built-in, simple layout for one

AutoCompleteTextView list item

arrayName is the name of the array or ArrayList

Retrieve the text from the AutoCompleteTextView just

like a TextView (tv.getText())

Creating a Custom List Item View

Create a new layout file (row.xml) that includes all the

widgets you want to appear in each row (item) of the

ListView

Probably (optional) want to create a class to manage the

data contained in one ListView item

Download and open the

CustomList starter

Create row.xml that

includes Header

(medium), sub-text and

icon (included in

drawable)

Review the Pet class

Page 9: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 9 of 10

Notes Activity

Create a class to store the custom list adapter (CLA).

Many online examples embed the class inside the

Main Activity

Class must extends BaseAdapter

Implement required methods

Cool technique: in the CLA, embed a class

(ViewHolder) that simply stores pointers to the

widgets in the row layout.

Just members (don’t designate private)

CLA members

Context context;

protected List<YourClass> thingList;

▪ Local pointer to the ArrayList

LayoutInflater inflater;

Define constructor that accepts values for all three

members public YourClass(Context context,

List< > lstName){

this.context = context;

this.inflater =

LayoutInflater.from(context); this.thingList = lstName;

}

Create

CustomListAdapterClass

extends BaseAdapter

Define ViewHolder class

with pointers to both

TextViews and

ImageView

Define members

Define constructor

getCount: return size of list

getItem: return (get) element at designated position

getItemId: just return 0

Code these and getView

Page 10: Introductory Mobile App Development - Volker Gaul Mobile Apps/Instructors Notes... · Introductory Mobile App Development 152-160 Unit 7 - ListViews Notes Activity Quick Links & Text

Instructor’s Notes Unit 7 - ListViews

Page 10 of 10

Notes Activity

getView ViewHolder holder;

if(convertView == null) {

holder = new ViewHolder();

convertView = this.inflater.inflate(

R.layout.row, parent, false);

//Define pointers for all widgets in holder Example:

holder.tvName = (TextView)convertView.findViewById(R.id.???);

convertView.setTag(holder); //used in else

} else {

Holder = (ViewHolder)convertView.getTag();

}

YourClass myObject = thingList.get(position);

//Set widgets in row to match corresponding members

//in myObject. Example

holder.tvName.setText(myObject.getName());

return convertView;

In Main Activity CustomListAdapter adapter = new

CustomListAdapter(this, yourArray);

lvList.setAdapter(adapter);

Add to Main Activity

Test