UI Adapter Elements
- Adapters provide a bridge between data and adapter views.
- Data -> Adapter -> AdapterView
- Examples of data are arrays, database tables.
- Examples of AdapterViews are ListView, Spinner,
GridView
- You can also write custom AdapterViews
- ListView
- Shows items in a vertically scrolling list.
- Attributes
- entries - reference to an array resource that populates the
ListView.
If used, then the ArrayAdapter subclass of ListAdapter is used
automatically.
- divider - drawable or color to draw between list items
- dividerHeight - divider height
- choiceMode - choice behaviour, one of none,
singleChoice, multipleChoice
- The items come from the adapter associated with the view.
- To display and select a single item you can use the adapter
android.R.layout.simple_list_item_1
- To select multiple items you can use the adapter
android.R.layout.simple_list_item_multiple_choice
- The OnItemClickListener allows you to listen for clicks on list elements in
onItemClick.
The position tells which element of the list was clicked.
The rowId is used when the list is created from an SQLite database cursor.
- Example, using an array resource of entries
MainActivity.java
activity_main.xml
strings.xml
- Spinner
- Displays one child at a time and lets the user pick among them.
- Attributes
- prompt - header text for list
- GridView
- Shows items in two-dimensional scrolling grid.
- Attributes
- numColumns - number of columns
- columnWidth - fixed width for columns
- horizontalSpacing and verticalSpacing - spacing between columns
and rows
- More complex and changing list items
- For lists whose items contain more than constants text and image items, you have to
write your own adapter
- The easiest way is to extend the SimpleAdapter class.
- Provide the data for the list in an ArrayList of Maps, e.g.,
HashMap.
- Use setViewValue to insert data into an adapter view element.
- Scrolling items that change
- If an adapter view has more elements that can fit on the screen, as you scroll
Android recycles the elements' views.
That optimization assumes that the views' layouts are all the same - only new data
is inserted into them.
- If you are going to change the views you need to extend an adapter class (e.g.,
ArrayAdapter or SimpleAdapter), and override the getView
method to ensure the view layout is correct for the requested position.
- Use setAdapter to use your own adapter.
- Example
MainActivity.java
activity_main.xml
grid_cell.xml
MyGridAdapter.java
dimens.xml
strings.xml