Showing a list of items is a very common pattern in mobile application. This pattern comes up often when I make a tutorial: I often need to interact with data, but I don’t want to spend a lot of time just on displaying that data when that’s not the point of the tutorial. So, what is the easiest way to display a simple list of values in Android like a list of string
s?
In the Android SDK, the widget used to show lists of items is a ListView
. A listview
must always get its data from an adapter
class. That adapter
class manages the layout used to display each individual item, how it should behave and the data itself. All the other widgets that display multiple items in the Android SDK, like the spinner and the grid, also need an adapter
.
When I was making the knitting row counter for my series on saving data with Android, I needed to show a list of all the projects in the database but I wanted to do the absolute minimum. The name of the projects are string
s so I used the ArrayAdapter
class from the Android SDK to display that list of string
s. Here, I have shown how to create the adapter
and set it in the listview
to display the list of items:
private ListView mListView;
@Override
protected void onStart()
{
super.onStart();
List<String> listViewValues = new ArrayList<String>();
for (Project currentProject : mProjects) {
listViewValues.add(currentProject.getName());
}
mListView = (ListView) findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1,
listViewValues.toArray(new String[listViewValues.size()]));
mListView.setAdapter(adapter);
}
After the adapter
for the list is set, you can also add an action to execute when an item is clicked. For the row counter application, clicking an item opens a new activity showing the details of the selected project.
private ListView mListView;
@Override
protected void onStart()
{
[...]
mListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent,
View view,
int position,
long id) {
Project project = mProjects.get(position);
Intent projectIntent = new Intent(MainActivity.this, ProjectActivity.class);
projectIntent.putExtra("project_id", project.getId());
MainActivity.this.startActivity(projectIntent);
}
If you need to go further than the default layout, you’ll need to create your custom layout and adapter to show the data the way you want it to, but what is shown here is enough to get started displaying data. If you want to run the example, you can find the complete RowCounter
project on my GitHub at http://github.com/CindyPotvin/RowCounter: the listview
is the MainActivity.java file.