Learn How to Customize List View in Android

Introduction

This article explains how to create a custom ListView in Android.

ListView

A ListView shows data in a list. The ListView loads the data using the Adapter class. The SetAdapter() method sets the data in a ListView.

In this application I have created the customized ListView that contains images and text.

Use the following procedure to create the project.

Go to "File" -> "AndroidApplicationProject".

image11

Step 1

Create an XML file activty_main with the following.

This XML file contains the ListView that you will to the MainActivty.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CustomListViewAndroidExample" >

<ListView
android:id="@+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="1"/>
</
RelativeLayout>

Step 2

Create another XML file customadapter.xml with the following.

This layout will inflate to the list view at run time. In this XML file I took two image views and a text view. In the image view I will the images and a link inside the text view.

<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:background="#cccccc"
android:paddingTop="0dip" >
<
TableRow>

<LinearLayout
android:layout_width="110dp"
android:layout_height="match_parent"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingTop="5dp" >

<ImageView

android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|top"
android:scaleType="centerCrop" />
</
LinearLayout>

<TableLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="top"
android:paddingTop="0dip" >
<
TableRow>

<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:layout_span="1"
android:layout_weight="1"
android:textColor="#000000"
android:textSize="16sp" />
</
TableRow>

<
TableRow>
<
TextView
android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center_vertical"
android:layout_marginLeft="10dip"
android:layout_marginTop="4dip"
android:layout_weight="1"
android:gravity="left"
android:text=""
android:textColor="#000000"
android:textSize="16sp" />
</
TableRow>

</TableLayout>
<
ImageView
android:layout_width="30dp"
android:layout_height="30dp"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"
android:background="@drawable/imagesthumb"
android:gravity="left"
android:scaleType="centerCrop" />

</
TableRow>

</
TableLayout>

In MainActivity you will first get the layout by calling the setContentView() method like this setContentView(R.layout.activity_main). Now create a setDataList() that set the data.

pasting

public void setDataList()
{
for (int i = 0; i < 11; i++) {
final ListModel listModel = 
new ListModel();
/******* First 
take data in model object ******/
listModel.setCompanyName("Company "+i);
listModel.setImage("image"+i);
listModel.setUrl("http:\\www."+i+".com");
/******** 
Take Model Object in ArrayList **********/
CustomArrlist.add( listModel );
}
}

After setting the data you will create an object of the CustomAdapter class. On creating the object of the CustomAdapter class the constructor of the CustomAdapter class will be called. You will the Activty, ListView, and res to the constructor of the CustomAdapter class.

setDataList();
Resources res =getResources();
list= ( ListView )findViewById( R.id.list ); // List defined
in XML ( See Below )

In this class you will create a method called onItemClick() so when you click the item in the list a toast message will be appear.

public void onItemClick(int mPosition)
{
ListModel tempValues = ( ListModel ) CustomArrlist.get(mPosition);
// SHOW ALERT
Toast.makeText(cActivity,""+tempValues.getCompanyName()+" Image:"+tempValues.getImage()+" Url:"+tempValues.getUrl(),Toast.LENGTH_LONG).show();
}

Step 3

Create a Java class MainActivity file with the following:

package com.customlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;

public class MainActivity extends Activity {
ListView list;
CustomAdapter customadapter;
public MainActivity cActivity = null;
public ArrayList<ListModel> CustomArrlist = new ArrayList<ListModel>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cActivity = this;
/********
Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
setDataList();
Resources res =getResources();
list= ( ListView )findViewById( R.id.list ); // List defined
in XML ( See Below )
/**************** Create
Custom Adapter *********/
customadapter=new CustomAdapter( cActivity, CustomArrlist,res );
list.setAdapter(customadapter);
}
/******
Function to set data in ArrayList *************/
public void setDataList()
{
for (int i = 0; i < 11; i++) {
final ListModel listModel =
new ListModel();
/******* First
take data in model object ******/
listModel.setCompanyName("Company "+i);
listModel.setImage("image"+i);
listModel.setUrl("http:\\www."+i+".com");
/********
Take Model Object in ArrayList **********/
CustomArrlist.add( listModel );
}
}
/***************** This
function used by adapter ****************/
public void onItemClick(int mPosition)
{
ListModel tempValues = ( ListModel ) CustomArrlist.get(mPosition)
;// SHOW ALERT
Toast.makeText(cActivity,""+tempValues.getCompanyName()+" Image:"+tempValues.getImage()+" Url:"+tempValues.getUrl(),Toast.LENGTH_LONG).show();
}
}

In a CustomAdapter class you will extend the BaseAdapter class and implement onClickListener. The construtor wiil give you the MainActivty, ArrayList, and reource. Now count the data in the arraylist by calling the getCount() method.

Step 4

Create another Java class file with the following:

package com.customlistview;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomAdapter extends BaseAdapter implements OnClickListener {
/***********
Declare Used Variables *********/
private Activity activity;
private ArrayList arrayList;
private static LayoutInflater inflater=null;
public Resources resources;
ListModel tempValues=null;
int i=0;
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity activity, ArrayList arrayList,Resources resLocal) {
/**********
Take ed values **********/
this.activity = activity;
this.arrayList=arrayList;
resources = resLocal;
/*********** Layout inflator
to call external xml layout () ***********/
inflater = ( LayoutInflater )activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What
is the size of ed Arraylist Size ************/
public int getCount() {
if(arrayList.size()<=0)
return 1;
return arrayList.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder
Class to contain inflated xml file elements *********/
public static class Viewholder{
public TextView text;
public TextView text1;
public TextView textWide;
public ImageView image;
}

//****** Depends upon data size called for each row , Create each ListView row *****/
public View getView(int position, View convertview, ViewGroup viewGroup) {
View view = convertview;
Viewholder holder;
if(convertview==null){
/****** Inflate tabitem.xml file
for each row ( Defined below ) *******/
view = inflater.inflate(R.layout.customadapter, null);
/****** View Holder
Object to contain tabitem.xml file elements ******/
holder =
new Viewholder();
holder.text = (TextView) view.findViewById(R.id.text);
holder.text1=(TextView)view.findViewById(R.id.text1);
holder.image=(ImageView)view.findViewById(R.id.image);

/************ Set holder with LayoutInflater ************/
view.setTag( holder );
}
else
holder=(Viewholder)view.getTag();
if(arrayList.size()<=0)
{
holder.text.setText("No Data");
}
else
{
/*****
Get each Model object from Arraylist ********/
tempValues=null;
tempValues = ( ListModel ) arrayList.get( position );
/************
Set Model values in Holder elements ***********/
holder.text.setText( tempValues.getCompanyName() );
holder.text1.setText( tempValues.getUrl() );
holder.image.setImageResource(
resources.getIdentifier(
"com.customlistview:drawable/"+tempValues.getImage()
,null,null));

/******** Set Item Click Listner for LayoutInflater for each row *******/

view.setOnClickListener(new OnItemClickListener( position ));
}
return view;
}
@Override
public void onClick(View v) {
Log.v("CustomAdapter", "=====Row button clicked=====");
}
/********* Called
when Item click in ListView ************/
private class OnItemClickListener implements OnClickListener{
private int myPosition;
OnItemClickListener(int position){
myPosition = position;
}

@Override
public void onClick(View arg0) {
MainActivity sct = (MainActivity)activity;
/****
Call onItemClick Method inside CustomListViewAndroidExample Class ( See Below )****/
sct.onItemClick(myPosition);
}
}
}


Step 5

Create a Java class file named ListModel with the following:

package com.customlistview;
public class ListModel {
private
 String CompName="";
private
 String Image="";
private
 String Url="";
/*********** 
Set Methods ******************/
public
 void setComName(String CompName)
{
this.CompName = CompName;
}
public
 void setImg(String Image)
{
this.Image = Image;
}
public
 void setUrl(String Url)
{
this.Url = Url;
}
/*********** 
Get Methods ****************/
public
 String getCompanyName()
{
return
 this.CompName;
}
public
 String getImage()
{
return
 this.Image;
}
public
 String getUrl()
{
return
 this.Url;
}
}

Step 6

Android Manifest.xml file

<?xml version="1.0" encoding="utf-8"?>
<
manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.customlistview"
android:versionCode="1"
android:versionName="1.0" >
<
uses-sdk

android:minSdkVersion="8"
android:targetSdkVersion="18" />
<
application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<
activity

android:name="com.customlistview.MainActivity"
android:label="@string/app_name" >
<
intent-filter>

<action android:name="android.intent.action.MAIN" />
<
category android:name="android.intent.category.LAUNCHER" />
</
intent-filter>
</
activity>
</
application>
</
manifest>

Step 7

image

Up Next
    Ebook Download
    View all
    Learn
    View all