Книга: Beginning Android
Using ArrayAdapter
Using ArrayAdapter
The easiest adapter to use is ArrayAdapter
— all you need to do is wrap one of these around a Java array or java.util.List
instance, and you have a fully-functioning adapter:
String[] items={this, is, a,
really, silly, list};
new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
The ArrayAdapter
constructor takes three parameters:
• The Context
to use (typically this will be your activity instance)
• The resource ID of a view to use (such as a built-in system resource ID, as previously shown)
• The actual array or list of items to show
By default, the ArrayAdapter
will invoke toString()
on the objects in the list and wrap each of those strings in the view designated by the supplied resource. android.R.layout.simple_list_item_1
simply turns those strings into TextView
objects. Those TextView
widgets, in turn, will be shown the list or spinner or whatever widget uses this ArrayAdapter
.
You can subclass ArrayAdapter
and override getView()
to “roll your own” views:
public View getView(int position, View convertView,
ViewGroup parent) {
if (convertView==null) {
convertView = new TextView(this);
}
convertView.setText(buildStringFor(position));
return(convertView);
}
Here, getView()
receives three parameters:
• The index of the item in the array to show in the view
• An existing view to update with the data for this position (if one already existed, such as from scrolling — if null, you need to instantiate your own)
• The widget that will contain this view, if needed for instantiating the view
In the previous example, the adapter still returns a TextView
, but uses a different behavior for determining the string that goes in the view. Chapter 9 will cover fancier ListViews
.
- Caveats using NAT
- Using Double Quotes to Resolve Variables in Strings with Embedded Spaces
- Data Binding Using the GridView Control
- Using the kill Command to Control Processes
- Installing Using a Network
- Using X
- Using a Display Manager
- Starting X from the Console by Using startx
- Using Fedora's switchdesk Client
- Using Environment Variables
- Using the Text Editors
- Using Man Pages