Filling the Layout with Data

Inserting data into the layout is typically done by binding the AdapterView class to an Adapter, which retireves data from an external source (perhaps a list that the code supplies or query results from the device's database).

The following code sample does the following:

1. Creates a Spinner with an existing View and binds it to a new ArrayAdapter that reads an array of colors from the local resources.

2. Creates another Spinner object from a View and binds it to a new SimpleCursorAdapter that will read people's names from the device contacts (see Contacts.People).

// Get a Spinner and bind it to an ArrayAdapter that references a String array. Spinner s1 = (Spinner) findViewById(R.id.spinner1); ArrayAdapter adapter = ArrayAdapter.createFromResource(

this, R.array.colors, android.R.layout.simple spinner item); adapter.setDropDownViewResource(android.R.layout.simple spinner dropdown item); s1.setAdapter(adapter);

// Load a Spinner and bind it to a data query. private static String[] PROJECTION = new String[] { People._ID, People.NAME

Spinner s2 = (Spinner) findViewById(R.id.spinner2);

Cursor cur = managedQuery(People.CONTENT_URI, PROJECTION, null, null); SimpleCursorAdapter adapter2 = new SimpleCursorAdapter(this, android.R.layout.simple spinner item, // Use a template that displays a

// text view cur, // Give the cursor to the list adatper new String[] {People.NAME}, //Map the NAME column in the people database to... new int[] {android.R.id.textl}); //The "textl" view defined in XML template adapter2.setDropDownViewResource(android.R.layout.simple spinner dropdown item); s2.setAdapter(adapter2);

Note that it is necessary to have the People._ID column in projection used with CursorAdapter or else you will get an exception.

If, during the course of your application's life, you change the underlying data that is read by your Adapter, you should call notifyDataSetChanged(). This will notify the attached View that the data has been changed and it should refresh itself.

0 0

Post a comment