As we mentioned, some view groups have UI. These objects typically subclass AdapterView. Examples include such as Gallery (an image selection widget) and ListView (a list of views). These objects have two jobs in common:
This is typically done by binding the class to an Adapter that gets its data from somewhere — either a list that the code supplies, or query results from the device's database.
// Get a Spinner and bind it to an ArrayAdapter that
// references a String array.
private String[] fruit = {"apples", "oranges", "lemons"}
Spinner s1 = (Spinner)findViewById(R.id.fruitlist);
s1.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner_1, fruit));
// Load a Spinner and bind it to a data query.
private String[] cols={android.provider.Contacts.PeopleColumns.NAME};
private Cursor cur = managedQuery(android.provider.Contacts.People.CONTENT_URI, cols, null, null);
s2.setAdapter(new CursorAdapter(cur, this));
This is done by setting the class's AdapterView.OnItemClickListener member to a listener and catching the selection changes.
// Create a message handling object as an anonymous class.
private OnItemClickListener mMessageClickedHandler = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id)
{
// Display a messagebox.
showAlert("You've got an event", "Clicked me!", "ok", false);
}
};
// Now hook into our object and set its onItemClickListener member
// to our class handler object.
mHistoryView = (ListView)findViewById(R.id.history);
mHistoryView.setOnItemClickListener(mMessageClickedHandler);