Monday, October 8, 2012

Java Design Patterns: Singleton Design Pattern



Java Design Patterns: Singleton Design Pattern


While searching on the net, I come across this good video tutorial, so posting it here. Not created by me.







JAVA Design Patterns: Difference between Builder, Factory, and Abstract Factory Patterns


JAVA Design Patterns: Difference between Builder, Factory, and Abstract Factory Patterns

While searching on the net, I come across this good video tutorial, so posting it here. Not created by me.




Wednesday, March 14, 2012

Change the background, text color for custom list view on focus and click

Change the background, text color for custom list view on focus and click

In this tutorial we will see how to change the background color on the custom list item, how to change the text style of text view etc.

We will use the same example which we have created in "How to create custom list view in android application" blog.

Once you done with the above custom list creation follow the below steps to achieve this - 



  • Create a highlight.png file and put that in drawable folder.
  • Create the selector for list item background, text 1 color, and text2 color as shown below under the drawable folder - 
listselector.xml - 

selector xmlns:android="http://schemas.android.com/apk/res/android" >
    item android:state_focused="true"
        android:drawable="@drawable/highlight" / >
    item android:state_pressed="true"
        android:drawable="@drawable/highlight" / >
    item android:state_selected="true"
        android:drawable="@drawable/highlight" / >
< /selector>

listitemline1_selector.xml - 

selector xmlns:android="http://schemas.android.com/apk/res/android" >
    item android:state_focused="true"
        android:color="#0e0c0a"/ >
    item android:state_pressed="true" android:color="#0e0c0a" /  >
    item android:state_selected="true" 
        android:color="#0e0c0a" / >
    item android:color="#b48f53" /  >
< /selector >

listitemline2_selector.xml - 

selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:state_focused="true"
        android:color="#0e0c0a"/>
    <item android:state_pressed="true" android:color="#0e0c0a"/>
    <item android:state_selected="true" 
        android:color="#0e0c0a"/>
    <item android:color="#725521"/>
selector

  • Now we need to assign these selector to individual list item and text views created on the hybridlist.xml file as shown below - 
hybridlist.xml - 

< ? 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:background="@drawable/listselector"
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:textColor="@drawable/listitemline1_selector" / >
TextView
android:id="@+id/text2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="11sp"
android:textColor="@drawable/listitemline2_selector" / >
< / LinearLayout>
< / LinearLayout>
  • Now run the application and you will see the same output as shown above. Same kind of selector you can apply to any view like Button, ImageView, Spinner etc.

Tuesday, March 13, 2012

Create your own customized spinner control with icon and text

How to create your own customized spinner control with icon and text

In this tutorial we will see how to create your own customized spinner view. In real life application, your UI designer will ask you to put some icon, with text having background etc. So to achieve this, you will need to create your own spinner view.





To achieve this, you will need need to place some icons in your drawable folder - motorola.png, google.png, microsoft.png, apple.png, yahoo.png, samsung.png.

  • First step to create an android project. I created with the "CustomerSpinnerDemo" and the package is "com.customspinnerdemo".
  • Copy the above mentioned images into res/drawable folder.
  • Create the string.xml file with the below content - 
string.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="hello">CustomSpinner Demo</string>
    <string name="prompt">Choose your selection</string>
    <string name="app_name">CustomSpinner Demo</string>
    <drawable name="white">#ffffff</drawable>
    <drawable name="black">#000000</drawable>
    <drawable name="green">#347C2C</drawable>
    <drawable name="pink">#FF00FF</drawable>
    <drawable name="violet">#a020f0</drawable>
    <drawable name="grey">#778899</drawable>
    <drawable name="red">#C11B17</drawable>
    <drawable name="yellow">#FFFF8C</drawable>
    <drawable name="PowderBlue">#b0e0e6</drawable>
    <drawable name="brown">#2F1700</drawable>
    <drawable name="Hotpink">#7D2252</drawable>
    <string name="select_Category">Select Category</string>
    <drawable name="darkgrey">#606060</drawable>
</resources>
  • Change the main.xml as follows - 
<?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:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
<Spinner
    android:id="@+id/spinner"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:drawSelectorOnTop="true"
    android:prompt="@string/prompt"
    />
</LinearLayout>
  • Create the row.xml as below under the layout folder - 
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="wrap_content"
 android:orientation="vertical"
 android:padding="3dip"
>
    <ImageView
         android:id="@+id/image"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:src="@drawable/icon"/>
    <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="3dip"
         android:layout_marginTop="2dip"
         android:textColor="@drawable/red"
         android:textStyle="bold"
         android:id="@+id/company"
         android:layout_marginLeft="5dip"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
     <TextView
         android:layout_toRightOf="@+id/image"
         android:padding="2dip"
         android:textColor="@drawable/darkgrey"
         android:layout_marginLeft="5dip"
         android:id="@+id/sub"
         android:layout_below="@+id/company"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"/>
</RelativeLayout>
  • Now need to change the main activity class as follows - 
package com.customspinnerdemo;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;

public class CustomSpinnerDemoActivity extends Activity {
String[] strings = {"Motorola","Google",
            "Microsoft", "Apple", "Yahoo","Samsung"};
    String[] subs = {"Mobile world","Google gives you everything",
            "Microsoft king of windows", "Apple you will love it", "Yahoo still strugling","Samsung good"};
    int arr_images[] = { R.drawable.motorola,
                         R.drawable.google, R.drawable.microsoft,
                         R.drawable.apple, R.drawable.yahoo, R.drawable.samsung}; 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Spinner mySpinner = (Spinner)findViewById(R.id.spinner);
        mySpinner.setAdapter(new MyAdapter(CustomSpinnerDemoActivity.this, R.layout.row, strings));
    }
    public class MyAdapter extends ArrayAdapter{
        public MyAdapter(Context context, int textViewResourceId,   String[] objects) {
            super(context, textViewResourceId, objects);
        }
        @Override
        public View getDropDownView(int position, View convertView,ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            return getCustomView(position, convertView, parent);
        }
        public View getCustomView(int position, View convertView, ViewGroup parent) {
            LayoutInflater inflater=getLayoutInflater();
            View row=inflater.inflate(R.layout.row, parent, false);
            TextView label=(TextView)row.findViewById(R.id.company);
            label.setText(strings[position]);
            TextView sub=(TextView)row.findViewById(R.id.sub);
            sub.setText(subs[position]);
            ImageView icon=(ImageView)row.findViewById(R.id.image);
            icon.setImageResource(arr_images[position]);
            return row;
            }
        }
}
  • Run the application and you will see the customer spinner control. You  can also attach the selector to change the background color, change the text etc.

How to add/manage menus in android application

How to add/manage menu in android application

Menues are very important part of any android applications, creation and managing those menu is little tricky in android. I will cover creation and managing menues in two steps - (You will need to create new android project and put 3 different play.png, record.png, soundon.png and stop.png into drawable folder)
  • Creating menu items
  • Managing menu items
Creating Menu Items - 





Creating the menu item is pretty simple. We need to override the "onCreateOptionsMenu(Menu menu)" method on your Activity class and need to add menues. Below is my activity class for your reference - 

package com.menuitem.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MenuItemTestActivity extends Activity {
private boolean isPlayStarted = false;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    menu.add(1, 101, 1, "Play").setIcon(R.drawable.play);
    menu.add(1, 102, 2, "Record").setIcon(R.drawable.record);
    menu.add(1, 103, 3, "Sound").setIcon(R.drawable.soundon);
    return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch(item.getItemId()) {
    case 101:
    Toast.makeText(getApplicationContext(), "Play clicked", Toast.LENGTH_LONG).show();
    isPlayStarted = true;
    break;
    case 102:
    Toast.makeText(getApplicationContext(), "Record clicked", Toast.LENGTH_LONG).show();
    break;
    case 103:
    Toast.makeText(getApplicationContext(), "Sound clicked", Toast.LENGTH_LONG).show();
    break;

    }
    return super.onOptionsItemSelected(item);
    }
}



Managing Menu Items -

Managing menu items are nothing but enabling and disabling some of the menu options, or adding the icons depending on the selected one etc. In this, we will change the menu item's icon and title depending on some conditions. So there is "onPrepareOptionsMenu" method which is called once user click on menu button and before displaying the menues in UI, this method is called. So you can include the code to change the title, icon of the menu item in this method. Apart from that, you can also enable/disable the menu item. Please see all the methods available for MenuItem. 

At the time of first call - 



After clicking on Play menu, and again press the menu button - 



My activity class will look like this - 

package com.menuitem.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

public class MenuItemTestActivity extends Activity {
private boolean isPlayStarted = false;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    menu.add(1, 101, 1, "Play").setIcon(R.drawable.play);
    menu.add(1, 102, 2, "Record").setIcon(R.drawable.record);
    menu.add(1, 103, 3, "Sound").setIcon(R.drawable.soundon);
    return super.onCreateOptionsMenu(menu);
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
    switch(item.getItemId()) {
    case 101:
    Toast.makeText(getApplicationContext(), "Play clicked", Toast.LENGTH_LONG).show();
    if (isPlayStarted) {
    isPlayStarted = false;
    }else {
    isPlayStarted = true;
    }
    break;
    case 102:
    Toast.makeText(getApplicationContext(), "Record clicked", Toast.LENGTH_LONG).show();
    break;
    case 103:
    Toast.makeText(getApplicationContext(), "Sound clicked", Toast.LENGTH_LONG).show();
    break;

    }
    return super.onOptionsItemSelected(item);
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    // TODO Auto-generated method stub
    MenuItem item = menu.findItem(101);
    if (isPlayStarted) {
    item.setTitle("Stop").setIcon(R.drawable.stop);
    } else {
    item.setTitle("Play").setIcon(R.drawable.play);
    }
    return super.onPrepareOptionsMenu(menu);
    }
}

Run the application and you will see the same screens as mentioned above.






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