Saturday, 16 February 2013

Creating Tabs using Fragments

    Tabs are excellent way to provide user access to multiple functionality very easily. Tabs were earlier implemented  with multiple activity inside one activity however with Honeycomb(thats long time back) Android discourages use of Activity inside Activity.

    With HoneyComb Android Sdk introduced Fragment .Fragments are very powerful part of Android SDK. Fragment is UI component that provides better control.They provide more modular control of different functionality inside Activity.

     However to provide backwards compatibility you can use Compatibility Package .

The primary classes related to fragments are:

The base class for all activities using compatibility-based fragment (and loader) features

The base class for all fragment definitions

The class for interacting with fragment objects inside an activity

The class for performing an atomic set of fragment operations

Now lets start with our example,
We will create Application with two Tabs. So for each tab we will need two Fragment.

here is our sample fragment

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class FragmentA extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
      TextView textView=new TextView(getActivity());
      textView.setText("Hello I am fragment A");
      return textView;

Similarly we can have FragmentB. Now we create our Activity that will be our tab container.For using Fragments inside Activity we must extend FragmentActivity.
//Some more imports

public class MainActivity extends FragmentActivity {
      //More code to come later
Now its time for layout of our Activity

<tabhost  xmlns:android=""
    android:background="@drawable/tab_activity_bg" >

    android:orientation="vertical" >

        <tabwidget android:id="@android:id/tabs"
            android:orientation="horizontal" />

            android:layout_weight="0" />

        <framelayout android:id="@+android:id/realtabcontent" 
           android:layout_weight="1" />
Please note the android:id it must be the same Now back to our Activity
    TabHost mTabHost;
    TabManager mTabManager;

    protected void onCreate(Bundle savedInstanceState) {
        mTabHost = (TabHost) findViewById(;
        mTabManager = new TabManager(this, mTabHost,;

             FragmentA.class, null);
             FragmentB.class, null);

Here TabManager mTabManager is only thing that we will we discussing
TabManager will manage our tabs for us.

import java.util.HashMap;

import android.content.Context;
import android.os.Bundle;
import android.view.View;

import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;

public class TabManager implements OnTabChangeListener {

    private final FragmentActivity mActivity;
    private final TabHost mTabHost;
    private final int mContainerId;
    private final HashMap mTabs = new  
    TabInfo mLastTab;

   static final class TabInfo {
       private final String tag;
       private final Class clss;
       private final Bundle args;
       private Fragment fragment;

       TabInfo(String _tag, Class _class, Bundle _args) {
           tag = _tag;
           clss = _class;
           args = _args;


  static class DummyTabFactory implements TabHost.TabContentFactory {
  private final Context mContext;

   public DummyTabFactory(Context context) {
       mContext = context;

   public View createTabContent(String tag) {
       View v = new View(mContext);
       return v;


  public TabManager(FragmentActivity activity, TabHost tabHost,
   int containerId) {
      mActivity = activity;
      mTabHost = tabHost;
      mContainerId = containerId;

  public void addTab(TabHost.TabSpec tabSpec, Class clss, Bundle args) {
      tabSpec.setContent(new DummyTabFactory(mActivity));
      String tag = tabSpec.getTag();

      TabInfo info = new TabInfo(tag, clss, args);

  // Check to see if we already have a fragment for this tab,probably
  // from a previously saved state. If so, deactivate it, because our
  // initial state is that a tab isn't shown.

      info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
      if (info.fragment != null && !info.fragment.isDetached()) {
          FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();

      mTabs.put(tag, info);

  public void onTabChanged(String tabId) {
      TabInfo newTab = mTabs.get(tabId);
      if (mLastTab != newTab) {
      FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
      if (mLastTab != null) {
          if (mLastTab.fragment != null) {
      if (newTab != null) {
          if (newTab.fragment == null) {
              newTab.fragment = Fragment.instantiate(mActivity,newTab.clss.getName(),newTab.args);
              ft.add(mContainerId, newTab.fragment, newTab.tag);
          } else {
      mLastTab = newTab;


  1. can u tell what is setTabView(); method for?

  2. Hello.
    What is setTabView(); in line 10 of MainActivity ?


  3. It's interesting that many of the bloggers your tips helped to clarify a few things for me as well as giving... very specific nice content.Android training in chennai with placement | Android Training in chennai |Android Training in Velachery

  4. This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic.
    Android Training in chennai | Android Training|Android Training in chennai with placement | Android Training in velachery

  5. Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
    full stack developer training in tambaram

    full stack developer training in velachery

  6. It is amazing and wonderful to visit your site.Thanks for sharing this information,this is useful to me...
    python training in rajajinagar
    Python training in btm
    Python training in marathahalli

  7. I always enjoy reading quality articles by an individual who is obviously knowledgeable on their chosen subject. Ill be watching this post with much interest. Keep up the great work, I will be back
    Blueprism training in Pune

    Blueprism online training

    Blue Prism Training in Pune

  8. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.

    Data Science Training in Chennai
    Data science training in bangalore
    Data science online training
    Data science training in pune

  9. Thanks for the good words! Really appreciated. Great post. I’ve been commenting a lot on a few blogs recently, but I hadn’t thought about my approach until you brought it up. 
    java training in chennai | java training in bangalore

    java online training | java training in pune

  10. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    angularjs-Training in pune

    angularjs-Training in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

  11. Hello there! This is my first comment here, so I just wanted to give a quick shout out and say I genuinely enjoy reading your articles.
    nebosh course in chennai

  12. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing.. Believe me I did wrote an post about tutorials for beginners with reference of your blog. 
    Microsoft Azure online training
    Selenium online training
    Java online training
    Java Script online training
    Share Point online training

  13. Excellant post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training