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.
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     tools:context=".CustomListViewAndroidExample" >  
  6.     <ListView  
  7.         android:id="@+id/list"  
  8.         android:layout_width="fill_parent"  
  9.         android:layout_height="wrap_content"  
  10.         android:layout_weight="1"/>  
  11. </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.
  1. <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="fill_parent"  
  3.     android:layout_height="wrap_content"  
  4.     android:layout_gravity="top"  
  5.     android:background="#cccccc"  
  6.     android:paddingTop="0dip" >  
  7.     <TableRow>  
  8.         <LinearLayout  
  9.             android:layout_width="110dp"  
  10.             android:layout_height="match_parent"  
  11.             android:paddingBottom="5dp"  
  12.             android:paddingLeft="10dp"  
  13.             android:paddingTop="5dp" >  
  14.             <ImageView  
  15.                 android:id="@+id/image"  
  16.                 android:layout_width="wrap_content"  
  17.                 android:layout_height="wrap_content"  
  18.                 android:layout_gravity="left|top"  
  19.                 android:scaleType="centerCrop" />  
  20.         </LinearLayout>  
  21.         <TableLayout  
  22.             android:layout_width="fill_parent"  
  23.             android:layout_height="wrap_content"  
  24.             android:layout_gravity="top"  
  25.             android:paddingTop="0dip" >  
  26.             <TableRow>  
  27.                 <TextView  
  28.                     android:id="@+id/text"  
  29.                     android:layout_width="wrap_content"  
  30.                     android:layout_height="wrap_content"  
  31.                     android:layout_gravity="left|center_vertical"  
  32.                     android:layout_marginLeft="10dip"  
  33.                     android:layout_marginTop="4dip"  
  34.                     android:layout_span="1"  
  35.                     android:layout_weight="1"  
  36.                     android:textColor="#000000"  
  37.                     android:textSize="16sp" />  
  38.             </TableRow>  
  39.             <TableRow>  
  40.                 <TextView  
  41.                     android:id="@+id/text1"  
  42.                     android:layout_width="wrap_content"  
  43.                     android:layout_height="wrap_content"  
  44.                     android:layout_gravity="left|center_vertical"  
  45.                     android:layout_marginLeft="10dip"  
  46.                     android:layout_marginTop="4dip"  
  47.                     android:layout_weight="1"  
  48.                     android:gravity="left"  
  49.                     android:text=""  
  50.                     android:textColor="#000000"  
  51.                     android:textSize="16sp" />  
  52.             </TableRow>  
  53.         </TableLayout>  
  54.         <ImageView  
  55.             android:layout_width="30dp"  
  56.             android:layout_height="30dp"  
  57.             android:layout_marginLeft="10dp"  
  58.             android:layout_marginTop="10dp"  
  59.             android:background="@drawable/imagesthumb"  
  60.             android:gravity="left"  
  61.             android:scaleType="centerCrop" />  
  62.     </TableRow>  
  63. </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.
  1. public void setDataList()  
  2. {  
  3.  for (int i = 0; i < 11; i++)   
  4.  {  
  5.   final ListModel listModel = new ListModel();  
  6.   /******* First take data in model object ******/  
  7.   listModel.setCompanyName("Company " + i);  
  8.   listModel.setImage("image" + i);  
  9.   listModel.setUrl("http:\\www." + i + ".com");  
  10.   /******** Take Model Object in ArrayList **********/  
  11.   CustomArrlist.add(listModel);  
  12.  }  
  13. }
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 Activity, ListView, and res to the constructor of the CustomAdapter class.
  1. setDataList();  
  2. Resources res = getResources();  
  3. 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 appear.
  1. public void onItemClick(int mPosition)   
  2. {  
  3.  ListModel tempValues = (ListModel) CustomArrlist.get(mPosition);  
  4.  // SHOW ALERT  
  5.  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:
  1. package com.customlistview;  
  2. import java.util.ArrayList;  
  3. import android.app.Activity;  
  4. import android.content.res.Resources;  
  5. import android.os.Bundle;  
  6. import android.widget.ListView;  
  7. import android.widget.Toast;  
  8. public class MainActivity extends Activity   
  9. {  
  10.  ListView list;  
  11.  CustomAdapter customadapter;  
  12.  public MainActivity cActivity = null;  
  13.  public ArrayList < ListModel > CustomArrlist = new ArrayList < ListModel > ();  
  14.   
  15.  @Override  
  16.  protected void onCreate(Bundle savedInstanceState)   
  17.  {  
  18.   super.onCreate(savedInstanceState);  
  19.   setContentView(R.layout.activity_main);  
  20.   cActivity = this;  
  21.   /******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/  
  22.   setDataList();  
  23.   Resources res = getResources();  
  24.   list = (ListView) findViewById(R.id.list); // List defined in XML ( See Below )  
  25.   /**************** Create Custom Adapter *********/  
  26.   customadapter = new CustomAdapter(cActivity, CustomArrlist, res);  
  27.   list.setAdapter(customadapter);  
  28.  }  
  29.  /****** Function to set data in ArrayList *************/  
  30.  public void setDataList()   
  31.  {  
  32.   for (int i = 0; i < 11; i++)   
  33.   {  
  34.    final ListModel listModel = new ListModel();  
  35.    /******* First take data in model object ******/  
  36.    listModel.setCompanyName("Company " + i);  
  37.    listModel.setImage("image" + i);  
  38.    listModel.setUrl("http:\\www." + i + ".com");  
  39.    /******** Take Model Object in ArrayList **********/  
  40.    CustomArrlist.add(listModel);  
  41.   }  
  42.  }  
  43.  /***************** This function used by adapter ****************/  
  44.  public void onItemClick(int mPosition)   
  45.  {  
  46.   ListModel tempValues = (ListModel) CustomArrlist.get(mPosition); // SHOW ALERT  
  47.   Toast.makeText(cActivity, "" + tempValues.getCompanyName() + " Image:" + tempValues.getImage() + " Url:" + tempValues.getUrl(), Toast.LENGTH_LONG).show();  
  48.  }  
In a CustomAdapter class, you will extend the BaseAdapter class and implement onClickListener. The constructor will give you the MainActivty, ArrayList, and resource. Now count the data in the arraylist by calling the getCount() method.
 
Step 4
 
Create another Java class file with the following:
  1. package com.customlistview;  
  2. import java.util.ArrayList;  
  3. import android.app.Activity;  
  4. import android.content.Context;  
  5. import android.content.res.Resources;  
  6. import android.util.Log;  
  7. import android.view.LayoutInflater;  
  8. import android.view.View;  
  9. import android.view.View.OnClickListener;  
  10. import android.view.ViewGroup;  
  11. import android.widget.BaseAdapter;  
  12. import android.widget.ImageView;  
  13. import android.widget.TextView;  
  14. public class CustomAdapter extends BaseAdapter implements OnClickListener   
  15. {  
  16.  /*********** Declare Used Variables *********/  
  17.  private Activity activity;  
  18.  private ArrayList arrayList;  
  19.  private static LayoutInflater inflater = null;  
  20.  public Resources resources;  
  21.  ListModel tempValues = null;  
  22.  int i = 0;  
  23.  /************* CustomAdapter Constructor *****************/  
  24.  public CustomAdapter(Activity activity, ArrayList arrayList, Resources resLocal)   
  25.  {  
  26.   /********** Take ed values **********/  
  27.   this.activity = activity;  
  28.   this.arrayList = arrayList;  
  29.   resources = resLocal;  
  30.   /*********** Layout inflator to call external xml layout () ***********/  
  31.   inflater = (LayoutInflater) activity.  
  32.   getSystemService(Context.LAYOUT_INFLATER_SERVICE);  
  33.  }  
  34.  /******** What is the size of ed Arraylist Size ************/  
  35.  public int getCount()   
  36.  {  
  37.   if (arrayList.size() <= 0)  
  38.    return 1;  
  39.   return arrayList.size();  
  40.  }  
  41.  public Object getItem(int position)  
  42.  {  
  43.   return position;  
  44.  }  
  45.  public long getItemId(int position)   
  46.  {  
  47.   return position;  
  48.  }  
  49.  /********* Create a holder Class to contain inflated xml file elements *********/  
  50.  public static class Viewholder   
  51.  {  
  52.   public TextView text;  
  53.   public TextView text1;  
  54.   public TextView textWide;  
  55.   public ImageView image;  
  56.  }  
  57.  //****** Depends upon data size called for each row , Create each ListView row *****/  
  58.  public View getView(int position, View convertview, ViewGroup viewGroup)   
  59.  {  
  60.   View view = convertview;  
  61.   Viewholder holder;  
  62.   if (convertview == null)  
  63.   {  
  64.    /****** Inflate tabitem.xml file for each row ( Defined below ) *******/  
  65.    view = inflater.inflate(R.layout.customadapter, null);  
  66.    /****** View Holder Object to contain tabitem.xml file elements ******/  
  67.    holder = new Viewholder();  
  68.    holder.text = (TextView) view.findViewById(R.id.text);  
  69.    holder.text1 = (TextView) view.findViewById(R.id.text1);  
  70.    holder.image = (ImageView) view.findViewById(R.id.image);  
  71.    /************ Set holder with LayoutInflater ************/  
  72.    view.setTag(holder);  
  73.   }  
  74.   else  
  75.    holder = (Viewholder) view.getTag();  
  76.   if (arrayList.size() <= 0)   
  77.   {  
  78.    holder.text.setText("No Data");  
  79.   }   
  80.   else   
  81.   {  
  82.    /***** Get each Model object from Arraylist ********/  
  83.    tempValues = null;  
  84.    tempValues = (ListModel) arrayList.get(position);  
  85.    /************ Set Model values in Holder elements ***********/  
  86.    holder.text.setText(tempValues.getCompanyName());  
  87.    holder.text1.setText(tempValues.getUrl());  
  88.    holder.image.setImageResource(  
  89.     resources.getIdentifier(  
  90.      "com.customlistview:drawable/" + tempValues.getImage(), nullnull));  
  91.    /******** Set Item Click Listner for LayoutInflater for each row *******/  
  92.    view.setOnClickListener(new OnItemClickListener(position));  
  93.   }  
  94.   return view;  
  95.  }  
  96.  @Override  
  97.  public void onClick(View v)   
  98.  {  
  99.   Log.v("CustomAdapter""=====Row button clicked=====");  
  100.  }  
  101.  /********* Called when Item click in ListView ************/  
  102.  private class OnItemClickListener implements OnClickListener   
  103.  {  
  104.   private int myPosition;  
  105.   OnItemClickListener(int position)   
  106.   {  
  107.    myPosition = position;  
  108.   }  
  109.   @Override  
  110.   public void onClick(View arg0)   
  111.   {  
  112.    MainActivity sct = (MainActivity) activity;  
  113.    /**** Call onItemClick Method inside CustomListViewAndroidExample Class ( See Below )****/  
  114.    sct.onItemClick(myPosition);  
  115.   }  
  116.  }  
Step 5
 
Create a Java class file named ListModel with the following:
  1. package com.customlistview;  
  2. public class ListModel   
  3. {  
  4.  private String CompName = "";  
  5.  private String Image = "";  
  6.  private String Url = "";  
  7.  /*********** Set Methods ******************/  
  8.  public void setComName(String CompName)   
  9.  {  
  10.   this.CompName = CompName;  
  11.  }  
  12.  public void setImg(String Image)   
  13.  {  
  14.   this.Image = Image;  
  15.  }  
  16.  public void setUrl(String Url)  
  17.  {  
  18.   this.Url = Url;  
  19.  }  
  20.  /*********** Get Methods ****************/  
  21.  public String getCompanyName()   
  22.  {  
  23.   return this.CompName;  
  24.  }  
  25.  public String getImage()  
  26.  {  
  27.   return this.Image;  
  28.  }  
  29.  public String getUrl()   
  30.  {  
  31.   return this.Url;  
  32.  }  
Step 6
 
Android Manifest.xml file
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <manifest xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     package="com.customlistview"  
  4.     android:versionCode="1"  
  5.     android:versionName="1.0" >  
  6.     <uses-sdk  
  7.         android:minSdkVersion="8"  
  8.         android:targetSdkVersion="18" />  
  9.     <application  
  10.         android:allowBackup="true"  
  11.         android:icon="@drawable/ic_launcher"  
  12.         android:label="@string/app_name"  
  13.         android:theme="@style/AppTheme" >  
  14.         <activity  
  15.             android:name="com.customlistview.MainActivity"  
  16.             android:label="@string/app_name" >  
  17.             <intent-filter>  
  18.                 <action android:name="android.intent.action.MAIN" />  
  19.                 <category android:name="android.intent.category.LAUNCHER" />  
  20.             </intent-filter>  
  21.         </activity>  
  22.     </application>  
  23. </manifest> 
Step 7
 
image


Similar Articles