In this tutorial I will show how to create a ListView and fill it with data.
1. Creating a row layout
First thing that we need to do is to create a row layout that will specify the way each row of our ListView is going to look like. To do that we need to create a new xml file (ringht click on the res folder of your project New->Android xml file) and name it row. Add the following code to your new row.xml file:
<?xmlversion="1.0"encoding="utf-8"?><TextViewxmlns:android="http://schemas.android.com/apk/res/android"android:textIsSelectable="true"android:id="@+id/r_text"android:layout_width="fill_parent"android:layout_height="fill_parent"android:padding="10dip"android:textColor="#ffffff"android:textSize="17sp"/>
2. Creating a ListView
Now we need to add a ListView element to our acitivy_main.xml file:
<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:orientation="vertical"android:layout_height="match_parent"android:background="#000000"><ListViewandroid:id="@+id/android:list"android:layout_width="fill_parent"android:layout_height="fill_parent"/></LinearLayout>
3. Adding items to ListView
The last thing that we need to do is to modify our Activity. Open MainActivity.java file of your project and modify the code like this:
packagelistviewexample.tuts.com;importandroid.os.Bundle;importandroid.app.ListActivity;importandroid.widget.ArrayAdapter;importjava.util.ArrayList;importjava.util.Collections;importjava.util.List;public classMainActivityextendsListActivity {privateString[]items;privateList<String>list;privateArrayAdapter<String>adapter; @Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); fillData(); } private void fillData() { String[] items = new String[] {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; list = new ArrayList<String>(); Collections.addAll(list, items); adapter = new ArrayAdapter<String>(this, R.layout.row, R.id.r_text, list); setListAdapter(adapter); } }
- because we want to display a ListView our Activity became a ListActivity:)
- in the fillData() method we first create an array of strings, that will later be placed in the list
- then we created an ArrayAdapter of string types and specified the following parameters of its constructor:
- current context
- row layout that has to be used for each row
- the ID of the TextView, in which our items will be placed (this ID is taken from row.xml file)
- items that need to be placed in it
- then we called setListAdapter() to let our ListActivity know how to fill the ListView
- Thats it!=)
DEMO
![]() |
| Android ListView Example |
Source code
Thank you for reading my blog!:)

