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.

How to create AutoComplete text view in Android Application

How to create AutoComplete text view in Android Application

In this tutorial, we will learn how to create Auto complete text view. In this example I am using hard corded value, in real world these value can be fetched from DB, RSS feed or from some other sources.

  • Create new Android project.
  • Add autotext view layout in main.xml file as shown below - 
          < ?xml version="1.0" encoding="utf-8"?>
          < LinearLayout
               android:id="@+id/widget32"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent"
               android:orientation="vertical"
               xmlns:android="http://schemas.android.com/apk/res/android">
               < AutoCompleteTextView
                      android:id="@+id/textAutoComplete"
                      android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
                      android:padding="15dp"
                      android:layout_marginLeft="20dp"
                      android:text=""
                      android:textSize="18sp" />
           < /LinearLayout>
  • Now need to attach the adapter to this auto complete view in activity class. I am using hard coded string array for demo purpose -
         package com.test.autocompletetest;

         import android.app.Activity;
         import android.os.Bundle;
         import android.widget.ArrayAdapter;
         import android.widget.AutoCompleteTextView;

         public class AutoCompleteTest extends Activity {
                private String[] sports = { "Cricket", "Football", "Table tenis", "Hockey", "Others" };
                AutoCompleteTextView acTextView;

                /** Called when the activity is first created. */
               @Override
               public void onCreate(Bundle savedInstanceState) {
                      super.onCreate(savedInstanceState);
                      setContentView(R.layout.main);
        
                      ArrayAdapter adapter = 
                                   new ArrayAdapter
                                           (this,android.R.layout.simple_dropdown_item_1line, sports);
        
                      acTextView = (AutoCompleteTextView)findViewById(R.id.textAutoComplete);
        
                       //Assigning the threshold value for auto complete view, so here once 
                      //user type one character then all the items from the adapter matching 
                      //that character will be displayed.
                      acTextView.setThreshold(1);
                     //Assigning the adapter to auto complete view.
                     acTextView.setAdapter(adapter);                
               }

        }
  • Run the application and you will see the auto complete text view will be populated with matching to your first character which you type.

How to create tabs in android application

How to create Tabs in android application

In this tutorial we will learn how to create tabs in android application and setting the height of the tabs.

Application will looks like this - 




  • Create a new android project.
  • Create 3 different layout and 3 different activity as given below - 

          Layouts - 

          tab1_layout.xml
          
           < ?xml version="1.0" encoding="utf-8"?>
           < LinearLayout
               xmlns:android="http://schemas.android.com/apk/res/android"
               android:orientation="vertical"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent" >

              < TextView android:text="Tab 1"
                  android:padding="15dip"
                   android:textSize="18dip"
                   android:layout_width="fill_parent"
                   android:layout_height="wrap_content" />

          < /LinearLayout>

          tab2_layout.xml

            < ?xml version="1.0" encoding="utf-8"?>
            < LinearLayout
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:orientation="vertical"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent">

               < TextView android:text="Tab 2"
                   android:padding="15dip"
                   android:textSize="18dip"
                   android:layout_width="fill_parent"
                   android:layout_height="wrap_content"/>
            < /LinearLayout>
          
          tab3_layout.xml

            < ?xml version="1.0" encoding="utf-8"?>
            < LinearLayout
               xmlns:android="http://schemas.android.com/apk/res/android"
               android:orientation="vertical"
               android:layout_width="fill_parent"
               android:layout_height="fill_parent">

              < TextView android:text="Tab 3"
                 android:padding="15dip"
                 android:textSize="18dip"
                 android:layout_width="fill_parent"
                 android:layout_height="wrap_content"/>
          < /LinearLayout>

       Activity Classes -

       Tab1.java

        package com.test.tabtest;

        import android.app.Activity;
        import android.os.Bundle;

        public class Tab1 extends Activity {
              public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.tab1_layout);
             }
       }

    Tab2.java

        package com.test.tabtest;

        import android.app.Activity;
        import android.os.Bundle;

        public class Tab2 extends Activity {
              public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.tab2_layout);
             }
       }

    Tab3.java

      package com.test.tabtest;

        import android.app.Activity;
        import android.os.Bundle;

        public class Tab3 extends Activity {
              public void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.tab3_layout);
             }
        }
  • Now create the main layout and main activity class which will extends from TabActivity as shown below - 

        Layout main.xml - 

        < ?xml version="1.0" encoding="utf-8"?>
        < LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"
             android:orientation="vertical"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent">
             < TextView android:text="This is tab test!!!"
                  android:padding="15dip"
                  android:textSize="18dip"
                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"/>
            < TabHost
                  android:id="@android:id/tabhost"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent">
                  < LinearLayout
                       android:orientation="vertical"
                       android:layout_width="fill_parent"
                       android:layout_height="fill_parent">
                       < TabWidget
                                android:id="@android:id/tabs"
                                android:layout_width="fill_parent"
                                android:layout_height="wrap_content" />
                     < FrameLayout
                                android:id="@android:id/tabcontent"
                                android:layout_width="fill_parent"
                                android:layout_height="fill_parent"/>
                  < /LinearLayout>
   
            < /TabHost>
       < /LinearLayout>

TabTest.java - main activity class - 

      package com.test.tabtest;

     import android.app.TabActivity;
     import android.content.Intent;
     import android.os.Bundle;
     import android.widget.TabHost;
     import android.widget.TabHost.TabSpec;

     public class TabTest extends TabActivity {
           /** Called when the activity is first created. */
          @Override
          public void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.main);
        
               TabHost tabHost = getTabHost();        
       
               TabSpec tab1spec = tabHost.newTabSpec("Tab1");
               tab1spec.setIndicator("Tab1");
               Intent tab1Intent = new Intent(this, Tab1.class);
               tab1spec.setContent(tab1Intent);

              TabSpec tab2spec = tabHost.newTabSpec("Tab2");
              tab2spec.setIndicator("Tab2");
              Intent tab2Intent = new Intent(this, Tab2.class);
              tab2spec.setContent(tab2Intent);

              TabSpec tab3spec = tabHost.newTabSpec("Tab3");
              tab3spec.setIndicator("Tab3");
              Intent tab3Intent = new Intent(this, Tab3.class);
              tab3spec.setContent(tab3Intent);

              // Adding all TabSpec to TabHost
              tabHost.addTab(tab1spec); 
              tabHost.addTab(tab2spec); 
              tabHost.addTab(tab3spec); 
        
             //Adjusting the tab height as per need.
             tabHost.getTabWidget().getChildAt(0).getLayoutParams().height=40;
             tabHost.getTabWidget().getChildAt(1).getLayoutParams().height=40;
             tabHost.getTabWidget().getChildAt(2).getLayoutParams().height=40;
       }
     }
  • Add entries in AndroidManifest.xml file for 3 new tab activities as shown below - 
         < ?xml version="1.0" encoding="utf-8"?>
         < manifest xmlns:android="http://schemas.android.com/apk/res/android"
              package="com.test.tabtest"
              android:versionCode="1"
              android:versionName="1.0">
              < application android:icon="@drawable/icon" android:label="@string/app_name">
                 < activity android:name=".TabTest"
                  android:label="@string/app_name">
                  < intent-filter>
                     < action android:name="android.intent.action.MAIN" />
                     < category android:name="android.intent.category.LAUNCHER" />
                   < /intent-filter>
                  < /activity>
        
                  < activity android:name=".Tab1" />

                 < activity android:name=".Tab2" />

                 < activity android:name=".Tab3" />

              < /application>
        < /manifest> 
  • Run the application and you will see the application having 3 different tabs and you can also put images for each tab by using below syntax - 
         Instead of 

                tab1spec.setIndicator("Tab1");

        Use 
  
               tab1spec.setIndicator("Tab1", getResources().getDrawable(R.drawable.icon));

How to zoom and drag images in Android app

How to zoom and drag images in Android app

This tutorial will teach you, how to create android application with image zoom and scroll facility.

First create the android project and follow the below steps. I used Android 1.6 for creating this example.

  • Add one image file in drawable folder with named "tempimage".
  • Create the main.xml with following configuration - 
xml version="1.0" encoding="utf-8"?>  
<FrameLayout  
   xmlns:android="http://schemas.android.com/apk/res/android"  
   android:id="@+id/root"  
   android:layout_width="fill_parent"  
   android:layout_height="fill_parent">  

 <ImageView android:id="@+id/imageview"  
       android:layout_width="fill_parent"  
       android:layout_height="fill_parent"  
       android:src="@drawable/tempimage"  
       android:scaleType="matrix"  
       android:adjustViewBounds="true"  
       android:layout_gravity="center">  
    ImageView>  
     
FrameLayout> 
  • Create the onlick listener as given below - 
package com.test.image.zoomtest;

import android.graphics.Matrix;  
import android.graphics.PointF;  
import android.util.FloatMath;  
import android.view.MotionEvent;  
import android.view.View;  
import android.view.View.OnTouchListener;  
import android.widget.ImageView;  
  
public class Touch implements OnTouchListener {  
  
 // These matrices will be used to move and zoom image  
 Matrix matrix = new Matrix();  
 Matrix savedMatrix = new Matrix();  
  
 // We can be in one of these 3 states  
 static final int NONE = 0;  
 static final int DRAG = 1;  
 static final int ZOOM = 2;  
 int mode = NONE;  
  
 // Remember some things for zooming  
 PointF start = new PointF();  
 PointF mid = new PointF();  
 float oldDist = 1f;  
  
   
 @Override  
 public boolean onTouch(View v, MotionEvent event) {  
  ImageView view = (ImageView) v;  
  // Dump touch event to log  
  dumpEvent(event);  
  
  // Handle touch events here...  
  switch (event.getAction() & MotionEvent.ACTION_MASK) {  
  case MotionEvent.ACTION_DOWN:  
   savedMatrix.set(matrix);  
   start.set(event.getX(), event.getY());  
   mode = DRAG;  
   break;  
  case MotionEvent.ACTION_POINTER_DOWN:  
   oldDist = spacing(event);  
   if (oldDist > 10f) {  
    savedMatrix.set(matrix);  
    midPoint(mid, event);  
    mode = ZOOM;  
   }  
   break;  
  case MotionEvent.ACTION_UP:  
  case MotionEvent.ACTION_POINTER_UP:  
   mode = NONE;  
   break;  
  case MotionEvent.ACTION_MOVE:  
   if (mode == DRAG) {  
    // ...      
    matrix.set(savedMatrix);  
    matrix.postTranslate(event.getX() - start.x, event.getY() - start.y);      
   } else if (mode == ZOOM) {  
    float newDist = spacing(event);  
    if (newDist > 10f) {  
     matrix.set(savedMatrix);  
     float scale = newDist / oldDist;  
     matrix.postScale(scale, scale, mid.x, mid.y);  
    }  
   }  
   break;  
  }  
  
  view.setImageMatrix(matrix);  
  return true; // indicate event was handled  
 }  
  
 /** Show an event in the LogCat view, for debugging */  
 private void dumpEvent(MotionEvent event) {  
  String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE",  
    "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };  
  StringBuilder sb = new StringBuilder();  
  int action = event.getAction();  
  int actionCode = action & MotionEvent.ACTION_MASK;  
  sb.append("event ACTION_").append(names[actionCode]);  
  if (actionCode == MotionEvent.ACTION_POINTER_DOWN  
    || actionCode == MotionEvent.ACTION_POINTER_UP) {  
   sb.append("(pid ").append(  
     action >> MotionEvent.ACTION_POINTER_ID_SHIFT);  
   sb.append(")");  
  }  
  sb.append("[");  
  for (int i = 0; i < event.getPointerCount(); i++) {  
   sb.append("#").append(i);  
   sb.append("(pid ").append(event.getPointerId(i));  
   sb.append(")=").append((int) event.getX(i));  
   sb.append(",").append((int) event.getY(i));  
   if (i + 1 < event.getPointerCount())  
    sb.append(";");  
  }  
  sb.append("]");  
 }  
  
 /** Determine the space between the first two fingers */  
 private float spacing(MotionEvent event) {  
  float x = event.getX(0) - event.getX(1);  
  float y = event.getY(0) - event.getY(1);  
  return FloatMath.sqrt(x * x + y * y);  
 }  
  
 /** Calculate the mid point of the first two fingers */  
 private void midPoint(PointF point, MotionEvent event) {  
  float x = event.getX(0) + event.getX(1);  
  float y = event.getY(0) + event.getY(1);  
  point.set(x / 2, y / 2);  
 }  
}  

  • Set the image view ontouch listener as given below - 
package com.test.image.zoomtest;

import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;



public class ImageZoomTestActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ImageView iv = (ImageView) findViewById(R.id.iv);
        iv.setOnTouchListener(new Touch());
    }
}
  • Now you are ready to run the application.