Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android Build a Blog Reader Android App Rebuilding from Scratch Adding Data for the List

Edward Poon
Edward Poon
9,313 Points

Need clarification on the 2nd argument of the ArrayAdapter

We initialized the variable new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mAndroidNames);

How does android know that we are referring to the list with android:id/list and puts our list of android names there? What if there were two lists? How would android know which list to put the mAndroidNames into?

Also, is there any reason why we are using predefined android:ids instead of ids that we define ourselves? i.e. why are we using "@android:id/list" which is a predefined android id instead of "@+id/<whatever id you want>

If we do choose to do the latter, how do we get the id for this?

1 Answer

ArrayAdapter takes the id of a layout resource as the 2nd param. The Android SDK provides a handful of pre-defined layouts we can use, one of which is android.R.layout.simple_list_item_1.

Conversely, if we defined a custom list item layout then we'd pass that to the ArrayAdapter constructor instead. Like, ArrayAdapter(this, R.layout.custom_layout), where custom_layout.xml is the filename of your new layout. The 3rd param of ArrayAdapter is your actual list of items. The framework uses that data to render a list of items based on the layout given as the 2nd param.

However, I believe if you're using ListActivity or ListFragment than the SDK is expecting to be provided with a layout that contains the designated @android:id/list. Those baked in classes are only built to handle a single list on-screen at once. If you have the multiple lists that you mentioned you'd define a layout that contains your own @+id/s. Then you'd programmatically reference the list (ListView list1 = findViewById(R.id.list1);), set its adapter (list1.setAdapter(adapter1)), and repeat for your other list.

So you will have created 2 ArrayAdapters with unique data and Android knows where to put what because setAdapter assigned them to unique views (list1, list2, etc.)