Getting to Know Array Adapter

The ArrayAdapter is the simplest of the adapters in Android. It specifically targets list controls and assumes that TextView controls represent the list items (the child views). Creating a new ArrayAdapter generally looks like this:

ArrayAdapter<String> adapter = new ArrayAdapter<String>(

this,android.R.layout.simple_list_item_1, new string[]{"sayed","satya"});

The constructor in the preceding code creates an ArrayAdapter where the TextView controls' data is represented by strings. Note that android.R.layout.simple_list_item_1 points to a TextView defined by the Android SDK.

ArrayAdapter provides a handy method that you can use, if the data for the list comes from a resource file. Listing 4-36 shows an example.

Listing 4-36. Creating an ArrayAdapter from a String-Resource File Spinner s2 = (Spinner) findViewById(;

adapter = ArrayAdapter.createFromResource(this, R.array.planets,android.R.layout.simple_spinner_item);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); s2.setAdapter(adapter);

<string-array name="planets"> <item>Mercury</item> <item>Venus</item> <item>Earth</item> <item>Mars</item> <item>Jupiter</item> <item>Saturn</item> <item>Uranus</item> <item>Neptune</item> <item>Pluto</item> </string-array>

Listing 4-36 shows that ArrayAdapter has a utility method called createFromResource() that can create an ArrayAdapter whose data source is defined in a string-resource file. Using this method allows you not only to externalize the contents of the list to an XML file, but also to use localized versions.

0 0

Post a comment