Saturday, September 1, 2012

Simple Listview example in android

Posted by Blogger Name. Category:

Creating Listview in android is pretty simple if you want a simple list. There are two way using it

  • Creating Listview using Listview control widget

  • Creating Listview using ListActivity 

If you are using second method then it implicitly give a Listview to add data using BaseAdapter. While using Listview we add data dynamically using Adapters like ArrayAdapter, CursorAdpter etc.
So now we will create a just simple Listview using ListActivity and we will bind data to Listview with the help of ArrayAdapter 

These are the basic steps to create a simple List

Step 1). Create one class to and extends ListActivity in-spite of activity

Step 2). Create one layout for row of Listview

 <TextView xmlns:android="http://schemas.android.com/apk/res/android"  
xmlns:tools="http://schemas.android.com/tools"
android:id="@android:id/text1"
android:layout_width="fill_parent"
android:layout_height="60dp"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="@android:color/white"
android:gravity="left|center_vertical"
android:padding="@dimen/padding_medium"
android:paddingLeft="10dp"
android:text="@string/hello_world"
android:textColor="@android:color/black"
android:textStyle="bold"
tools:context=".ListActivity" />

Now you output will be like this screen shot 

Simple Listview
Listview
Step 4) Binding Data to ListView

      private String item[] = { "This is list Item1", "This is list Item2",  
"This is list Item3", "This is list Item4", "This is list Item5",
"This is list Item6" };
private void TakeOneArrayAdapterToaddData() {
ArrayAdapter<String> adpter = new ArrayAdapter<String>(this,
R.layout.activity_list);
for (String str : item)
adpter.add(str);
getListView().setAdapter(adpter);
}

Step 4) Performing click event on Listview's item 

set click listener on Listview and override method

      @Override  
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Builder builder = new AlertDialog.Builder(this);
builder.setMessage(item[position] + " is clicked.");
builder.setPositiveButton("OK", null);
builder.show();
}


Selected ListView'Item
Selected Item
                                                             

                                                                        Download Source Code

Next Article Creating ListView with Image and Label

0 comments:

Post a Comment

◄ Posting Baru Posting Lama ►