Wednesday, February 8, 2012

How to create custom list view in android application

How to create custom list view in android application

In this tutorial we will learn how to create custom list view, since the standart list view is having only one line which doesn't have facility to format as we want. So the solution here is to create your own custom list view.

Here I am creating a custom list view which will have Two lines to display the information. Also you can add as many controls you want easily to the each item in the list view.

After the run the custom list will be displayed like this -



To create the above custom list, need to follow below steps.


  • First create new Android Project.
  • First you need to create a simple pojo class which will be kind of data holder for your list item. In my case I took the example of Employe, below is my pojo class -
         package com.test.customlistviewtest;

         import java.util.ArrayList;
         import java.util.List;

         /**
          * @author Raghvendra Kamlesh
          *
         */
         public class Employe {
        private static List employeList =  new ArrayList();
        private String name;
        private String department;

        public Employe(String name, String department) {
    this.name = name;
    this.department = department;
        }

       public static List getEmployeList() {
    return employeList;
       }

       public String getName() {
    return name;
       }
       public void setName(String name) {
    this.name = name;
       }
       public String getDepartment() {
       return department;
       }
       public void setDepartment(String department) {
    this.department = department;
      }
         }

  • Create a new layout file which will be representation of the one item in the list. In my case I am using two text controls to create one item in the list. Here is my hybridlist.xml file which you need to create inside the layout folder.
         < ?xml version="1.0" encoding="utf-8"?>
         < LinearLayout
              android:layout_width="fill_parent"
              android:layout_height="fill_parent"
              android:gravity="center_vertical"
               android:descendantFocusability="blocksDescendants"
                xmlns:android="http://schemas.android.com/apk/res/android">
              < LinearLayout
                     android:layout_width="fill_parent"
                     android:layout_height="wrap_content"
                     android:orientation="vertical"
                     android:layout_weight="1">
                      < TextView
                          android:id="@+id/text1"
                          android:layout_width="fill_parent"
                          android:layout_height="wrap_content"
                          android:textSize="15sp"
                          android:textStyle="bold"
                          android:text="Text view 1" />
                      < TextView
                          android:id="@+id/text2"
                          android:layout_width="fill_parent"
                          android:layout_height="wrap_content"
                          android:textSize="11sp"
                          android:text="Text view 2" />
                  < /LinearLayout>
       < /LinearLayout>
  • Now need to create a EmployeAdapter class which should extends from 
    BaseAdapter, and need to provide the implementation of its abstract methods. This is the actual adapter class where we will provide our own view to the custom list.

    package com.test.customlistviewtest;


    import java.util.List;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.LinearLayout;
    import android.widget.TextView;

    /**
     * @author Raghvendra Kamlesh
     *
     */
    public class EmployeAdapter extends BaseAdapter {
    private List employeList;
    private Context context;

    /**
    */
    public EmployeAdapter(Context context, List employeList) {
    this.context = context;
    this.employeList = employeList;
    }

    /* (non-Javadoc)
    * @see android.widget.Adapter#getCount()
    */
    public int getCount() {
    // TODO Auto-generated method stub
    return employeList.size();
    }

    /* (non-Javadoc)
    * @see android.widget.Adapter#getItem(int)
    */
    public Object getItem(int position) {
    // TODO Auto-generated method stub
    return employeList.get(position);
    }

    /* (non-Javadoc)
    * @see android.widget.Adapter#getItemId(int)
    */
    public long getItemId(int position) {
    // TODO Auto-generated method stub
    return position;
    }

    /* (non-Javadoc)
    * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
    */
    public View getView(int position, View convertView, ViewGroup parent) {
                  Employe e = employeList.get(position);
            
                  convertView = (LinearLayout)LayoutInflater.from(context).inflate
                          (R.layout.hybridlist, null);
                  TextView text1 = (TextView)convertView.findViewById(R.id.text1);
                  text1.setText(e.getName());
                  TextView text2 = (TextView) convertView.findViewById(R.id.text2);
                  text2.setText(e.getDepartment());
            
                  return convertView;
    }
    }

  • Change the main.xml as below - 
           < ?xml version="1.0" encoding="utf-8"?>
           < LinearLayout
                      android:layout_width="fill_parent"
                      android:layout_height="fill_parent"
                      android:orientation="vertical"
                      xmlns:android="http://schemas.android.com/apk/res/android">
                      < TextView
                                 android:layout_width="fill_parent"
                                 android:layout_height="wrap_content"
                                 android:textSize="20sp"
                                 android:textStyle="bold"
                                 android:padding="5dp"
                                 android:text="Custom List Example" />
                      < ListView
                                 android:id="@+id/lstEmploye"
                                 android:layout_width="fill_parent"
                                 android:layout_height="wrap_content"
                                 android:padding="10dp" />
           < /LinearLayout>
  • Now in main activity class, you will need to assign employe adapter to list view and then new employe adapter class will take care of displaying hybride.xml layout for each and every item in the list. Also you can capture the on select event, and identify which item user has selected.
          package com.test.customlistviewtest;

          import android.app.Activity;
          import android.os.Bundle;
          import android.view.View;
          import android.widget.AdapterView;
          import android.widget.AdapterView.OnItemClickListener;
          import android.widget.ListView;
          import android.widget.Toast;

          public class CustomListViewTestActivity extends Activity {
          ListView lstEmployeView;
                    /** Called when the activity is first created. */
                    @Override
                   public void onCreate(Bundle savedInstanceState) {
                            super.onCreate(savedInstanceState);
                            setContentView(R.layout.main);
        
                            Employe.getEmployeList().add(new Employe("John leun", "Engineering"));
                            Employe.getEmployeList().add(new Employe("Meddy yu chan", "Marketing"));
                            Employe.getEmployeList().add(new Employe("David federal desulmati", "Engineering"));
                            Employe.getEmployeList().add(new Employe("Denny folkerl mo", "Sales"));
                            Employe.getEmployeList().add(new Employe("Daniel soln cary", "Admin"));
        
                            lstEmployeView = (ListView)findViewById(R.id.lstEmploye);
        
                            lstEmployeView.setAdapter(new EmployeAdapter(this, Employe.getEmployeList()));
        
                            lstEmployeView.setOnItemClickListener(new OnItemClickListener() {
                                public void onItemClick(AdapterView arg0, View arg1, int arg2, long arg3) {
                                Employe selectedEmploye = Employe.getEmployeList().get(arg2);
                                Toast.makeText(getApplicationContext(), "Selected Employe is ==> " + selectedEmploye.getName(), Toast.LENGTH_LONG).show();
                                }
          });
                    }
         }
  • Now the example is completed, you can run the example and see the newly created custom list view. There are so many other possibility also can be achieve by writing our own custom layout for list view. We can add images, check boxes, radio buttons and many other controls inside the hybridlayout.xml file to include that for each and every list item.
If you want to do customization of the list item like changing the background color, text color on focus or on select see the "Change the background, text color for custom list view on focus and click" post.

No comments:

Post a Comment