Simulator Screenshots

How To Create A Custom Listview - Android Example

DOWNLOAD SOURCE CODE
 

In this Android Example creating a custom adapter to create a custom ListView.

Showing how to show images and text in each ListView row.

Follow Structure :

          1.  Create Model to save data for each listview row.

          2.  Save data to Model.

          3.  Take each Model class object in an ArrayList.

          4.  Create Custom adapter. Pass Arraylist to adapter. Adapter called recursively for each listview row and get data from Model inside ArrayList.

          5.  Call xml file inside Adapter for each Listview row ( Use of LayoutInflater inside Adapter ).

          6.  Inside MainActivity Set Adapter to ListView

          7.  Define List in AnadroidMainifest.xml file

 

Project Structure :

 

Custom_ListView_project_sketch

 

NOW START  CODING :

 

ListModel.java file

Create Model to save each ListView row data.

 


 public class ListModel {
    
            private  String CompanyName="";
            private  String Image="";
            private  String Url="";
            
            /*********** Set Methods ******************/
            
            public void setCompanyName(String CompanyName)
            {
                this.CompanyName = CompanyName;
            }
            
            public void setImage(String Image)
            {
                this.Image = Image;
            }
            
            public void setUrl(String Url)
            {
                this.Url = Url;
            }
            
            /*********** Get Methods ****************/
            
            public String getCompanyName()
            {
                return this.CompanyName;
            }
            
            public String getImage()
            {
                return this.Image;
            }
        
            public String getUrl()
            {
                return this.Url;
            }    
      }

 

======================================================================================================

 

 CustomAdapter.java file

Create Custom adapter. Pass Arraylist to adapter. Adapter called recursively for each listview row and get data from Model inside ArrayList.

 




       /********* Adapter class extends with BaseAdapter and implements with OnClickListener ************/
       public class CustomAdapter extends BaseAdapter   implements OnClickListener {
                
                /*********** Declare Used Variables *********/
                private Activity activity;
                private ArrayList data;
                private static LayoutInflater inflater=null;
                public Resources res;
                ListModel tempValues=null;
                int i=0;
                
                /*************  CustomAdapter Constructor *****************/
                public CustomAdapter(Activity a, ArrayList d,Resources resLocal) {
                    
                       /********** Take passed values **********/
                        activity = a;
                        data=d;
                        res = resLocal;
                    
                        /***********  Layout inflator to call external xml layout () ***********/
                         inflater = ( LayoutInflater )activity.
                                                     getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    
                }
            
                /******** What is the size of Passed Arraylist Size ************/
                public int getCount() {
                    
                    if(data.size()<=0)
                        return 1;
                    return data.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 parent) {
                    
                    View vi = convertView;
                    ViewHolder holder;
                    
                    if(convertView==null){
                        
                        /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
                        vi = inflater.inflate(R.layout.tabitem, null);
                        
                        /****** View Holder Object to contain tabitem.xml file elements ******/

                        holder = new ViewHolder();
                        holder.text = (TextView) vi.findViewById(R.id.text);
                        holder.text1=(TextView)vi.findViewById(R.id.text1);
                        holder.image=(ImageView)vi.findViewById(R.id.image);
                        
                       /************  Set holder with LayoutInflater ************/
                        vi.setTag( holder );
                    }
                    else  
                        holder=(ViewHolder)vi.getTag();
                    
                    if(data.size()<=0)
                    {
                        holder.text.setText("No Data");
                        
                    }
                    else
                    {
                        /***** Get each Model object from Arraylist ********/
                        tempValues=null;
                        tempValues = ( ListModel ) data.get( position );
                        
                        /************  Set Model values in Holder elements ***********/

                         holder.text.setText( tempValues.getCompanyName() );
                         holder.text1.setText( tempValues.getUrl() );
                          holder.image.setImageResource(
                                      res.getIdentifier(
                                      "com.androidexample.customlistview:drawable/"+tempValues.getImage()
                                      ,null,null));
                         
                         /******** Set Item Click Listner for LayoutInflater for each row *******/

                         vi.setOnClickListener(new OnItemClickListener( position ));
                    }
                    return vi;
                }
                
                @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 mPosition;
                    
                    OnItemClickListener(int position){
                         mPosition = position;
                    }
                    
                    @Override
                    public void onClick(View arg0) {

              
                      CustomListViewAndroidExample sct = (CustomListViewAndroidExample)activity;

                     /****  Call  onItemClick Method inside CustomListViewAndroidExample Class ( See Below )****/

                        sct.onItemClick(mPosition);
                    }               
                }   
            }


 

Explanation :

       getView Method :  Called each time for data size( ArrayList size ).

                EXAMPLE :     if data size is 11 then get view methed called 11 times to produce each row.

       LayoutInflater :  Inflate (Add) view/xml file for ListView Row.

       Holder :    Contain Inflated / added xml Elaments.

 

tabitem.xml file used in CustomAdapter.java

Custom ListView each row show according to this xml file.

 


         <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/bar_bg"
                 android:paddingTop="0dip" android:layout_gravity="top"
               >
              <TableRow>
                  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
                        xmlns:tools="http://schemas.android.com/tools"
                        android:layout_width="110dp"
                        android:layout_height="match_parent"
                        android:paddingLeft="10dp"
                        android:paddingTop="5dp"
                        android:paddingBottom="5dp"
                        >
                    <ImageView
                        android:layout_height="wrap_content"
                        android:layout_width="wrap_content"
                        android:layout_gravity="left|top"  
                        android:scaleType="centerCrop"
                        android:id="@+id/image"
                        
                        />
                    </LinearLayout>
        <TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:paddingTop="0dip" android:layout_gravity="top"
                  >
                  <TableRow>       
                     <TextView
                          android:id="@+id/text"
                          android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:layout_weight="1" android:layout_gravity="left|center_vertical"
                          android:textSize="16sp"
                          android:layout_marginLeft="10dip"
                          android:layout_marginTop="4dip"
                          android:textColor="#000000"
                          android:layout_span="1"
                          />
                    </TableRow>
                    <TableRow>          
                       <TextView
                          android:text=""
                          android:id="@+id/text1"
                          android:layout_height="wrap_content"
                          android:layout_width="wrap_content"
                          android:layout_weight="1"
                          android:layout_gravity="left|center_vertical"
                          android:textSize="16sp"
                          android:textColor="#000000"
                          android:layout_marginLeft="10dip"
                          android:layout_marginTop="4dip"
                          android:gravity="left"/>
                    </TableRow>
                  </TableLayout>
                    
                     <ImageView
                        android:layout_height="30dp"
                        android:layout_width="30dp"
                        android:scaleType="centerCrop"
                        android:background="@drawable/dislike1"
                        android:layout_marginLeft="10dp"
                        android:layout_marginTop="10dp"
                        android:gravity="left"
                        />
             </TableRow>
      </TableLayout>

 


==================================================================================================

 

CustomListViewAndroidExample.java file

This is Main Activity class, Inside this activity Set Adapter to ListView.

 


           public class CustomListViewAndroidExample extends Activity {
            
                ListView list;
                CustomAdapter adapter;
                public  CustomListViewAndroidExample CustomListView = null;
                public  ArrayList<ListModel> CustomListViewValuesArr = new ArrayList<ListModel>();
                
                @Override
                protected void onCreate(Bundle savedInstanceState) {


                    super.onCreate(savedInstanceState);
                    setContentView(R.layout.activity_custom_list_view_android_example);
                    
                    CustomListView = this;
                    
                    /******** Take some data in Arraylist ( CustomListViewValuesArr ) ***********/
                    setListData();
                    
                    Resources res =getResources();
                    lis t= ( ListView )findViewById( R.id.list );  // List defined in XML ( See Below )
                    
                    /**************** Create Custom Adapter *********/
                    adapter=new CustomAdapter( CustomListView, CustomListViewValuesArr,res );
                    list.setAdapter( adapter );
                    
                }
            
                /****** Function to set data in ArrayList *************/
                public void setListData()
                {
                    
                    for (int i = 0; i < 11; i++) {
                        
                        final ListModel sched = new ListModel();
                            
                          /******* Firstly take data in model object ******/
                           sched.setCompanyName("Company "+i);
                           sched.setImage("image"+i);
                           sched.setUrl("http:\\www."+i+".com");
                           
                        /******** Take Model Object in ArrayList **********/
                        CustomListViewValuesArr.add( sched );
                    }
                    
                }
               

               /*****************  This function used by adapter ****************/
                public void onItemClick(int mPosition)
                {
                    ListModel tempValues = ( ListModel ) CustomListViewValuesArr.get(mPosition);
  

                   // SHOW ALERT                  

                    Toast.makeText(CustomListView,
                            ""+tempValues.getCompanyName()
                              +" 
Image:"+tempValues.getImage()
                              +" 
Url:"+tempValues.getUrl(),
                            Toast.LENGTH_LONG)
                    .show();
                }
       }


 

activity_custom_list_view_android_example.xml file

Define ListView to contain data

 


    <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> 

 

 

Share this: