Simple List Activity
In most mobile applications, you’re going to be presenting your users a list of something. Most of the time, it’s not as simple as an array of strings; your data may be stored away in a local Sqlite database, or perhaps behind a RESTful API. In any case, we’ll be taking a look at what it takes to begin with a simple ListActivity that can be easily updated later on.
Create a new Android Project (1.1+) and name the activity MyListActivity (or whatever you prefer.) Run the app to ensure you’re working off a valid clean slate.
Next, modify your activity (MyListActivity) to extend the Android class ListActivity and adjust your code to look like the following:
So far, so good. We have a method to create our list adapter, so essentially, our onCreate() method is done. Let’s move on to adapters.
Adapters basically glue a collection of objects to an activity, usually by providing a mapping or instructions on how to render each object in the list for the activity. In our case, we have a simple list of strings, so our adapter is pretty straightforward (and in fact, is already provided by Android: ArrayAdapter)
Modify your createAdapter() method to look like the following:
This encapsulates everything we need to get an adapter up and running. Typically here we may make a call-out to data, which may be a Sqlite query or a RESTful GET request, but for now we’re using simple strings. We create an ArrayAdapter and specify three things: Context, Layout, and Data.
The Context is simply where the list came from. In our app it’s simple, but sometimes it can get a little complex when you’re passing intents back and forth across activities, so this is used to keep a reference to the owner activity at all times.
The Layout is where the data will be rendered (and how it will look.) We’re using a built-in Android layout for our needs (simple_list_item_1).
The Data is what will be rendered, and is a simple list of strings.
The Layout is where the data will be rendered (and how it will look.) We’re using a built-in Android layout for our needs (simple_list_item_1).
The Data is what will be rendered, and is a simple list of strings.
Final result should look like the following:
Run the app, and you should see something like this:
And there you have a nice introduction to a ListActivity that can be expanded upon by focusing on thecreateAdapter() method. In Part 2, we’ll explore using more complex Object lists and custom Adapters, as well as a brief introduction to the layout files. Thanks for reading!
No comments:
Post a Comment