How to create a scrolling ListView in android?

By | March 12, 2011

ListView is like a tableView in iPhone or iOS . In this example i will show you how to add a String Array in to the ListView and also make the listView Scrollable.

First the xml file . Here the line

android:scrollbars=”vertical”

will make the scrolling vertically

<?xml version="1.0" encoding="utf-8"?>
<relativeLayout
android:id="@+id/widget32"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
	<listView
			android:id="@+id/listview"
			android:scrollbars="vertical"
			android:layout_width="fill_parent"
			android:layout_height="200dip"
			android:layout_gravity="fill_vertical"
			android:layout_alignParentTop="true"
			>
		</listView>

</relativeLayout>

Now the java file

package com.Ch.Example.pack;

import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

public class Example extends Activity
{
    /** Called when the activity is first created. */
	ListView list;
	private List<string> List_file;
	public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        List_file =new ArrayList<string>();
        list = (ListView)findViewById(R.id.listview);

        CreateListView();
    }
	private void CreateListView()
	{
		 List_file.add("Coderzheaven");
		 List_file.add("Google");
		 List_file.add("Android");
		 List_file.add("iPhone");
		 List_file.add("Apple");
		 //Create an adapter for the listView and add the ArrayList to the adapter.
		 list.setAdapter(new ArrayAdapter<string>(Example.this, android.R.layout.simple_list_item_1,List_file));
		 list.setOnItemClickListener(new OnItemClickListener()
		   {
				@Override
				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3)
				{
					//args2 is the listViews Selected index
				}
		   });
	}
}

The screen will be like this

Here is a other useful posts related to listviews.

1. ListView with Sections in android.
2. A Simple Layout with two listViews.

2 thoughts on “How to create a scrolling ListView in android?

  1. Pingback: ListView with Sections in android. | Coderz Heaven

  2. soap90king.skyrock.com

    Hello there! This post could not be written much
    better! Looking at this post reminds me of my previous roommate!
    He continually kept talking about this. I most certainly will send this article to him.

    Fairly certain he’s going to have a good read. Thanks for sharing!

    Reply

Leave a Reply

Your email address will not be published.