Android Simple ListView Example

ListView is a view group that displays a list of scrollable items. The list items are inserted to the list using an Adapter that pulls content from a source such as an array. It is a very basic layout element of Android applications and is one of things you will use quite often. Here we will explore a very simple example of how to implement a listview in your Android app. So, let’s get started.

First, create a new Android project in Eclipse by going through File -> New -> Android Application Project. Then, enter your project details and create a blank or empty activity with activity name as “MainActivity” and layout name as “activity_main” and click Finish. You Android project will be created in the workspace.

Now, open “activity_main.xml” layout file from res/layout/ folder into its source view and put this code in it:

activity_main.xml

In this layout file, we just created a LinearLayout with vertical orientation and a ListView as its child. Note we set our ListView id as “@android:id/list” which provides a default list layout from the Android SDK.

Now, open your source file for “MainActivity.java” from the folder src/ and then your package name folder. Put this code in the file.

MainActivity.java

Here we are extending our MainActivity from ListActivity and setting its view to our layout created earlier “activity_main”. Then, we are creating a string array named “actressArray” containing items to fill our listview with. After that we are creating an ArrayAdapter with three arguments – “this” for our MainActivity context, “android.R.layout.simple_list_item_1” for simple list item layout provided in Android SDK and “actressArray” we just created. Then we are passing out adapter to our list by settings its adapter. Basically, what happens is that items from our array are given the default look and put into our listview.

Now that our simple listview is created, lets go a little further. We create a ListView object named “actressList” with reference to our default listview. Then we use the anonymous inner type to get our feedback. When a list item in clicked, its position is passed as argument and through that we get its value and pass it to a String variable “actress”. Then we use a toast message to display which item was clicked.

Now, run the application and you will have an output similar to this:

Android Simple ListView Example

That’s all, we have just created a simple list in our Android app from a string array. Whenever a list item is click, we get a feedback. Instead of using toast message, we can also start a new activity or do something else. Hope this tutorial was helpful!

Note: In some scenarios, you have to extend your Main Activity from Activity (or ActionBarActivity) instead of ListActivity. In that case, this method is not applicable. Follow this tutorial for such a case.

Related Posts

Add Comment