Android Tech

The more we share, the more we get

ListView (Part 1) – Create a simple List View in Android


In this post is a very simple demo about how to create a list view in Android application.

1. First we create a List view control and put it on your screen. In this example, I put it in main screen (main.xml)

<?xml version=”1.0″ encoding=”utf-8″?>

<LinearLayout android:id=”@+id/LinearLayout01″
android:layout_width=”fill_parent” android:layout_height=”fill_parent”
xmlns:android=”http://schemas.android.com/apk/res/android”&gt;
<ListView android:id=”@+id/ListView01″ android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
</LinearLayout>

2. After that, you will insert data into it when the application loaded. Open main activity file and insert these lines:

private ListView lv1;
private String lv_arr[] = { “Android”, “iPhone”, “BlackBerry”, “AndroidPeople” };

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
lv1 = (ListView) findViewById(R.id.ListView01);
// By using setAdpater method in listview we an add string array in list.
lv1.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, lv_arr));
}

And the final result will like this:

Some notes:

When you click on one item, you will find out that the color of selection area is not fill out the width of the item. It just a part like this:

So, to avoid this, you should modify the value of attribute “android:layout_width” from “wrap_content” to “fill_parent”. And the result will look better.

You can download source code here

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: