Android ListView Tutorials
A ListView is a ViewGroup which displays a list of
items can scrollable.The list items can
are inserted automatically onto the list using a ListAdapter.
In this tutorial,i'm going to teach you creating a
ListView and showing a toast message on the selected list item.
Step by step tutorial:
1.Create a new
project
Project Name : SimpleListView
Package : com.roney.simplelistview
Main Activity : SimpleListViewActivity.java
Build Target : Android 2.2
2.After creating the project,Open your MAinActivity class.Here it is
SimpleListViewActivity.java and extends the class from ListActivity.
public class
SimpleListViewActivity extends ListActivity
{
}
3.Now we nee to
have a string resource file to store all list items.So
create a XML file under
res/values/ folder and save it as list_data.xml
and enter the following code.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array
name="social_sites">
<item>Facebook</item>
<item>Twitter</item>
<item>Yahoo</item>
<item>Google+</item>
<item>Orkut</item>
</string-array>
</resources>
4.Now we need to
create the layout to show each items in the ListView.
Create a xml file under res/layout folder as list_item.xml
Create a xml file under res/layout folder as list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/label"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold" >
</TextView>
5.Open your main
activity,ie.SimpleListViewActivity.java and type
the
following code.
SimpleListViewActivity.java
package com.roney.simplelistview;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class SimpleListViewActivity extends ListActivity
{
// defining array to
store string resources
String[] social_sites;
@Override
public void
onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// storing string
resources into Array
social_sites = getResources().getStringArray(R.array.social_sites);
// Binding resources
Array to ListAdapter
this.setListAdapter(new ArrayAdapter<String>
(this,R.layout.list_item, R.id.label,social_sites));
}
@Override
protected void onListItemClick(ListView
l, View v, int position, long id)
{
Toast.makeText(this,
"You have selected : "+social_sites[position],
Toast.LENGTH_SHORT).show();
}
}
6.Now its time to run the
project.The result will show in the emulator is
shown bellow.
The result show a ListView
with list of array items.When a item in the list is selected you will see a
toast message.
"Your comments and suggestions please"
0 comments:
Post a Comment