RSS

Android : Tabs. The Fragment Way

04 Oct

If you’re the die-hard follower (yes, I said “the” because the stats says there is) of this blog, you would have probably noticed that I’ve been M.I.A for awhile.  We’ll, it’s mainly been because I’ve been working on an Android project with a super-toit deadline which we managed to launch JIT on to the Marketplace.

Now that the first phase of that project is over, I’m now able to reflect a bit on the code that was produced and share here some of my experiences and (source).

In this first installment, I want to illustrate how to create a Tab activity using Fragments since, going-forward, it is suggested that building on Fragments will ensure your app is compatible with pre-Honeycomb, Honeycomb and Ice Cream Sandwich (tablet and phone) OS versions (see this article).  Remember, in Android 2.x Tabs are presented as classic “filing” tabs, while on Android 3.x and higher tabs are represented in the ActionBar UI component.

Requirements

To implement a Tabbed, using fragments on devices running Android 2.1 or higher, you’ll need to include the Android Compatibility library.  In my example, I’m using Compatibility library v4

Step-by-Step

  1. Define TabHost layout
  2. Define Tab fragment layouts
  3. Define Tab fragments
  4. Define main fragment activity

The Code

Define the TabHost layout

The tabbed UI layout consists of 4 parts: TabHost, TabWidget, FrameLayout and the content layout. tabs_layout.xml illustrates how they stack up.  You’ll notice that the FrameLayout id=realtabcontent is a child of a FrameLayout. Isn’t this redundant? The answer is no, be attaching out fragments to this FrameLayout.

<?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">
	<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:orientation="horizontal"
	            android:layout_width="fill_parent"
	            android:layout_height="wrap_content"
	            android:layout_weight="0"
	            />

	        <FrameLayout
	            android:id="@android:id/tabcontent"
	            android:layout_width="0dp"
	            android:layout_height="0dp"
	            android:layout_weight="0"/>

	        <FrameLayout
	            android:id="@+android:id/realtabcontent"
	            android:layout_width="fill_parent"
	            android:layout_height="0dp"
	            android:layout_weight="1"/>
	    </LinearLayout>
	</TabHost>
</LinearLayout>

Define Tab fragment layouts

Next, we define out fragment layouts (i.e the content layout for each tab). Nothing special here…you’d define your layout as if the layout was for a stand-alone activity.  Below is tab_frag1_layout.xml (tab_frag2_layout.xml and tab_frag3_layout.xml are exactly the same except the have different colours specified for their backgrounds).

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

Define Tab fragment classes

Each tab content fragment needs to extend Fragment and inflate it’s corresponding layout. As you’ll see later, each fragment is instantiated by the main FragmentActivity using the fragment manager.  Below is the definition of TabFragment1.java (TabFragment2.java and TabFragment3.java are exactly the same, except they inflate their respective layouts)

package com.andy.fragments.tabs;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.andy.R;

/**
 * @author mwho
 *
 */
public class Tab1Fragment extends Fragment {
	/** (non-Javadoc)
	 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
	 */
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if (container == null) {
            // We have different layouts, and in one of them this
            // fragment's containing frame doesn't exist.  The fragment
            // may still be created from its saved state, but there is
            // no reason to try to create its view hierarchy because it
            // won't be displayed.  Note this is not needed -- we could
            // just run the code below, where we would create and return
            // the view hierarchy; it would just never be used.
            return null;
        }
		return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
	}
}

Define the main FragmentActivity

TabsFragmentActivity.java is where everything comes together.  Firstly, you’ll notice that TabsFragmentActivity extends FragementActivity instead of Activity.

Next, we look at onCreate(…). This is the starting point of our activity.  The first step is to inflate the tabbed layout as defined in tabs_layout.xml. In step 2, we initialise the tabs.  This involves invoking setup() on the TabHost view, adding tabs, save some extrinsic tab info (TabInfo) into a map and then setting the first tab content as active.

       /**
	 * Step 2: Setup TabHost
	 */
	private void initialiseTabHost(Bundle args) {
		mTabHost = (TabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup();
        TabInfo tabInfo = null;
        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab 1"), ( tabInfo = new TabInfo("Tab1", Tab1Fragment.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab 2"), ( tabInfo = new TabInfo("Tab2", Tab2Fragment.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab 3"), ( tabInfo = new TabInfo("Tab3", Tab3Fragment.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        // Default to first tab
        this.onTabChanged("Tab1");
        //
        mTabHost.setOnTabChangedListener(this);
	}

I created a static helper method to add the tabs to the TabHost as defined by an instance of TabHost.TabSpec.  Each TabSpec is initialised with an instance of TabFactory (TabFactory is an inner class that extends TabContentFactory that creates an empty View as a placeholder for our fragments).  Next, we detach the Fragement associated with the tab we’re trying to add. Then, finally we add the TabSpec to the TabHost.

	private static void addTab(TabsFragmentActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
		// Attach a Tab view factory to the spec
	tabSpec.setContent(activity.new TabFactory(activity));
        String tag = tabSpec.getTag();

        // 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.
        tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
        if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
            FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
            ft.detach(tabInfo.fragment);
            ft.commit();
            activity.getSupportFragmentManager().executePendingTransactions();
        }

        tabHost.addTab(tabSpec);
	}

Finally, we need to handle the onTabChanged(…) event handler where we’ll create, attach or detach the fragments when a specific tab is clicked.  When onTabChanged(…) is invoked a the tab’s tag value is passed as a parameter.  We use this tag value to look up the TabInfo instance we stored in initialiseTabHost(…), which has a reference to the fragment associated with the implied tab.

Our responsibility here is to detach the fragment for the tab we’re moving from, to the fragment for the tab that was clicked and to do nothing if the user clicked the active tab.

If the tab’s fragment doesn’t exist, it’s created using reflection on fragmentName.class on the FragmentManager by adding the fragment to the FrameLayout id=realcontent.

	public void onTabChanged(String tag) {
		TabInfo newTab = this.mapTabInfo.get(tag);
		if (mLastTab != newTab) {
			FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
            if (mLastTab != null) {
                if (mLastTab.fragment != null) {
                	ft.detach(mLastTab.fragment);
                }
            }
            if (newTab != null) {
                if (newTab.fragment == null) {
                    newTab.fragment = Fragment.instantiate(this,
                            newTab.clss.getName(), newTab.args);
                    ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
                } else {
                    ft.attach(newTab.fragment);
                }
            }

            mLastTab = newTab;
            ft.commit();
            this.getSupportFragmentManager().executePendingTransactions();
		}
    }

Here’s the big picture

package com.andy.fragments.tabs;

import java.util.HashMap;

import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.TabContentFactory;

import com.andy.R;

/**
 * @author mwho
 *
 */
public class TabsFragmentActivity extends FragmentActivity implements TabHost.OnTabChangeListener {

	private TabHost mTabHost;
	private HashMap mapTabInfo = new HashMap();
	private TabInfo mLastTab = null;

	private class TabInfo {
		 private String tag;
         private Class clss;
         private Bundle args;
         private Fragment fragment;
         TabInfo(String tag, Class clazz, Bundle args) {
        	 this.tag = tag;
        	 this.clss = clazz;
        	 this.args = args;
         }

	}

	class TabFactory implements TabContentFactory {

		private final Context mContext;

	    /**
	     * @param context
	     */
	    public TabFactory(Context context) {
	        mContext = context;
	    }

	    /** (non-Javadoc)
	     * @see android.widget.TabHost.TabContentFactory#createTabContent(java.lang.String)
	     */
	    public View createTabContent(String tag) {
	        View v = new View(mContext);
	        v.setMinimumWidth(0);
	        v.setMinimumHeight(0);
	        return v;
	    }

	}
	/** (non-Javadoc)
	 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
	 */
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Step 1: Inflate layout
		setContentView(R.layout.tabs_layout);
		// Step 2: Setup TabHost
		initialiseTabHost(savedInstanceState);
		if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab")); //set the tab as per the saved state
        }
	}

	/** (non-Javadoc)
     * @see android.support.v4.app.FragmentActivity#onSaveInstanceState(android.os.Bundle)
     */
    protected void onSaveInstanceState(Bundle outState) {
        outState.putString("tab", mTabHost.getCurrentTabTag()); //save the tab selected
        super.onSaveInstanceState(outState);
    }

	/**
	 * Step 2: Setup TabHost
	 */
	private void initialiseTabHost(Bundle args) {
		mTabHost = (TabHost)findViewById(android.R.id.tabhost);
        mTabHost.setup();
        TabInfo tabInfo = null;
        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab1").setIndicator("Tab 1"), ( tabInfo = new TabInfo("Tab1", Tab1Fragment.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab 2"), ( tabInfo = new TabInfo("Tab2", Tab2Fragment.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab 3"), ( tabInfo = new TabInfo("Tab3", Tab3Fragment.class, args)));
        this.mapTabInfo.put(tabInfo.tag, tabInfo);
        // Default to first tab
        this.onTabChanged("Tab1");
        //
        mTabHost.setOnTabChangedListener(this);
	}

	/**
	 * @param activity
	 * @param tabHost
	 * @param tabSpec
	 * @param clss
	 * @param args
	 */
	private static void addTab(TabsFragmentActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
		// Attach a Tab view factory to the spec
		tabSpec.setContent(activity.new TabFactory(activity));
        String tag = tabSpec.getTag();

        // 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.
        tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
        if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
            FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
            ft.detach(tabInfo.fragment);
            ft.commit();
            activity.getSupportFragmentManager().executePendingTransactions();
        }

        tabHost.addTab(tabSpec);
	}

	/** (non-Javadoc)
	 * @see android.widget.TabHost.OnTabChangeListener#onTabChanged(java.lang.String)
	 */
	public void onTabChanged(String tag) {
		TabInfo newTab = this.mapTabInfo.get(tag);
		if (mLastTab != newTab) {
			FragmentTransaction ft = this.getSupportFragmentManager().beginTransaction();
            if (mLastTab != null) {
                if (mLastTab.fragment != null) {
                	ft.detach(mLastTab.fragment);
                }
            }
            if (newTab != null) {
                if (newTab.fragment == null) {
                    newTab.fragment = Fragment.instantiate(this,
                            newTab.clss.getName(), newTab.args);
                    ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);
                } else {
                    ft.attach(newTab.fragment);
                }
            }

            mLastTab = newTab;
            ft.commit();
            this.getSupportFragmentManager().executePendingTransactions();
		}
    }

}

The AndroidManifest.xml

Say something about AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.andy"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".fragments.tabs.TabsFragmentActivity"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Summary

TODO

About these ads
 
163 Comments

Posted by on October 4, 2011 in Android

 

Tags: , , , ,

163 responses to “Android : Tabs. The Fragment Way

  1. Benoit

    November 12, 2011 at 23:16

    Hi,
    As I never visited your blog before, I’m not “the” reader.
    But I found what I needed in this post, so thank you.

    Benoit

     
  2. Antonio

    December 18, 2011 at 21:39

    Very useful post, thank you!
    Could you attach a zip file with the code to the article for an easy download?

     
    • mitchwongho

      December 20, 2011 at 21:49

      Hi Antonio,

      I encourage you to get the source from Github, then you’ll have all the sample code.

       
      • Ben W

        June 26, 2012 at 05:48

        Hey, you keep replying to get the source code from Github but quite a few of us are having trouble finding a link to it, can you provide one please?

         
  3. ofir

    December 22, 2011 at 10:31

    Hey,

    First of all, tnx.

    A question: what if one of the tabs content has a button in it? Where do I put the onClick of that button? According to your code, the onClick will have to be found inside the TabsFragmentActivity class, which is very nasty thing to do… putting all the functions that handle the UI events of each tab content inside the tabs container…

    Maybe I got it all wrong? If not, how can I put the onClick handler of each tab content in the tab’s class (such as “Tab2Fragment”) and not in the TabsFragmentActivity class?

    Thanks in advance.

     
    • mitchwongho

      December 22, 2011 at 15:47

      If I were to add a button to Fragment having the id @+id/frag1_button, then you can register for button click events
      as follows:

      public class Tab1Fragment extends Fragment {
      	/* (non-Javadoc)
      	 * @see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
      	 */
      	@Override
      	public View onCreateView(LayoutInflater inflater, ViewGroup container,
      			Bundle savedInstanceState) {
      		if (container == null) {
                  // We have different layouts, and in one of them this
                  // fragment's containing frame doesn't exist.  The fragment
                  // may still be created from its saved state, but there is
                  // no reason to try to create its view hierarchy because it
                  // won't be displayed.  Note this is not needed -- we could
                  // just run the code below, where we would create and return
                  // the view hierarchy; it would just never be used.
                  return null;
              }
      		LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
      		// Register for the Button.OnClick event
      		Button b = (Button)theLayout.findViewById(R.id.frag1_button);
      		b.setOnClickListener(new View.OnClickListener() {
      			
      			@Override
      			public void onClick(View v) {
      				Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGTH_LONG).show();
      				
      			}
      		});
      		return theLayout;
      	}
      }
      
       
      • Anuja Piayadigama (@AnujAroshA)

        May 24, 2012 at 06:26

        Thanks for asking this question and thanks for the reply. It really helped me.

         
      • kiduxa

        May 5, 2013 at 04:54

        Thank you sooooooooooo much!!! you made my day!! =)

         
  4. ofir

    December 22, 2011 at 15:58

    Yes, dynamically assignment will work, but there’s no way of doing this by using the XML way, right? Besides, I think of just using an ActionBar instead (thank u for introducing me the Compatibility lib) to act as a tab bar. Is this a common thing to do if I want to support version 2.2 and up?

     
  5. Stalski

    December 31, 2011 at 15:32

    Great post for starters like me :)

     
  6. Gaurav

    January 13, 2012 at 15:58

    Hi,

    Is there any way i can set the content of another activity with in the tab structure when tab activity is called for the first time. like default page kinda.

     
    • mitchwongho

      January 18, 2012 at 15:48

      It is possible to independently update the fragments in a TabView via the FragmentManager or TabHost

       
  7. ghouse

    January 14, 2012 at 14:40

    hi i have read your post and i got a doubt suppose if i have a listview in first tab and when ever i click any item i need to move to another screen but in the same tab how can i do that one

     
    • mitchwongho

      January 18, 2012 at 15:54

      Hi,

      It sounds like you are looking at implementing Fragments within Fragments. I’m not sure this is possible as a View/Layout is inflated into a Fragment.

      If I’m mistaken and there is an example of an application that his implemented what you’re looking for, please share it here. I’d love to see it in action.

       
      • ghouse

        February 1, 2012 at 13:32

        Hi mitchwongho
        if fragments with in fragments is not possible then how can we implement a tabview like contacts in any android phone

         
      • ranjith

        June 5, 2013 at 06:55

        if u got the answer for what ghouse asked.. then pls share i am struggling with the same doubt…

         
  8. Shane

    January 17, 2012 at 01:25

    Thanks so much for a great post. It’s the best one that I could find. If I wanted to customize the tabs, say for instance, change background color to a gradient or image. Where would I do that?

     
  9. ramiz

    January 20, 2012 at 11:25

    This is great. Very simple and easy to understand.

    Much appreciated.

     
  10. atc

    January 31, 2012 at 23:30

    Hi, I’m trying to build this but i get these errors:

    The method isDetached() is undefined for the type Fragment

    The method detach(Fragment) is undefined for the type FragmentTransaction

    The method attach(Fragment) is undefined for the type FragmentTransaction

    Type mismatch: cannot convert from Object to TabsFragmentActivity.TabInfo

    Any help on how to fix this would be appreciated. Thanks

     
    • Mark

      March 5, 2012 at 18:52

      Hay – i got same problem exactly – did you get a fiX?

       
  11. Alex

    February 7, 2012 at 14:43

    It is possible to provide a link to Github, where we can find all code?, I have some missunderstands…

     
  12. larry

    February 7, 2012 at 17:28

    Thank you for putting this together. I dropped your code into Eclipse and get 1 error:

    from eclipse:

    Type mismatch: cannot convert from Object to TabsFragmentActivity.TabInfo TabsFragmentActivity.java /TabsFragment/src/com/genovese/tabsfragment line 130 Java Problem

    line 130: TabInfo newTab = this.mapTabInfo.get(tag);

    Any ideas? Thanks!

     
    • Prabakaran G

      July 6, 2012 at 08:52

      you can typecast it, like this.

      TabInfo newTab = (TabInfo) this.mapTabInfo.get(tag);

       
  13. Renaud FAVIER

    February 9, 2012 at 13:36

    Hello !
    I try to do exactly that in a project of mine, but I’ve got an “Error inflating class fragment” that come up. I’ve spent a lot of time of this problem and I can’t see the solution.
    Could you have a look on it, i’ve post on stackOverflow :

    http://stackoverflow.com/questions/9208220/replacing-tabactivity-by-fragment-error-inflating-class-fragment

    thanks a lot !

     
  14. Sohne Mann

    February 10, 2012 at 16:29

    Hi, i have a problem to understand your code. i can run this code!
    I will make a app whit tabs 3 Contacts = tab 1 , Chat = tab 2 and GPS Location = tab 3.
    How can i add Activity to Tabfragment?

    TabhostActivity is deprecated an i will use Fragments.

    Can you help me pleace?

     
  15. memmers

    February 15, 2012 at 08:57

    Hey, would you recommend using this approach if one was to have grid style icons to each fragment using a ViewPager? if so, how would you add the icons to each fragment? is this something that should be done from xml or from the java code directly?

    thanks for your help

     
  16. Alex

    March 2, 2012 at 16:13

    onTabChanged(String tag)….

    I have added some extra fragments for one tab. From Tab1Fragment I navigate to Tab1.1Fragment, from here I naviget to Tab1.2Fragment and so on….using this:

    FragmentManager fragmentManager = getFragmentManager();
    FragmentTransaction ft = fragmentManager.beginTransaction();

    Tab1.1Fragment fragment = new Tab1.1Fragment();
    ft.replace(R.id.realtabcontent, fragment, ” “);

    ft.addToBackStack(null);
    ft.commit();

    The problem is that when Tab1.1Fragment or Tab1.2Fragment is active and I change the tab this fragment does not detach. How can I solve this?

     
    • rui_helder

      January 25, 2013 at 19:32

      I have the same problem.
      Did someone manage to fix it ?

       
  17. Max

    March 8, 2012 at 02:03

    Hi,

    I have the same error as larry for :
    TabInfo newTab = this.mapTabInfo.get(tag);

    Type mismatch: cannot convert from Object to TabsFragmentActivity.TabInfo

    Did someone manage to fix it ?

     
    • Twinkle

      February 27, 2013 at 05:26

      Solution A:
      Type cast to TabInfo:
      TabInfo newTab = (TabInfo)this.mapTabInfo.get(tag);

      Solution B: (Go back to declared variables at the top)
      Refer to “HashMap mapTabInfo = new HashMap();”
      Change “HashMap” to HashMap

       
  18. Eugenia Gabrielov

    March 12, 2012 at 07:19

    Thanks for the excellent explanations in this guide. It helped me figure out how to implement TabHost / Fragments efficiently. Best of luck with your other ongoing projects!

     
  19. sandhya

    March 20, 2012 at 07:05

    MainTabActivity(with out tab activity)

    Tab1

    Fragment1 -> Fragment2 -> Fragment3

    Tab2

    Fragment4->Fragment6

    Tab3

    Fragment6 -> Fragment7

    It should support all versions and phone and tabs.

    Is there any solution for these??

     
    • khawar

      February 19, 2013 at 07:59

      @sandhya, did you find any solution for it? I’m doing the same, can you share it with me if you’ve done it successfully, thanks

       
    • ranjith

      June 5, 2013 at 07:03

      yaa i almost find out an answer… but am not sure is it right or not. but it is working…

      you must write code on ur ist fragment. that is fragment1.

      in fragment1 u have a button click or list view onclick listener. so on the onClick function. u write the below code.

      undle myBundle = new Bundle();
      myBundle.putString(“result”,”result” );
      Fragment fragment = Fragment.instantiate(context,WebResult.class.getName(), myBundle);
      FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
      ft.replace(R.id.realtabcontent, fragment);
      ft.addToBackStack(“tag name of fragment1″);
      ft.commit();

      and let me know if u already find out other solutions… pls……

       
  20. Brian

    March 22, 2012 at 17:57

    Hi, thanks for posting this. I wanted to point out something what seems to be a mistake:

    “You’ll notice that the FrameLayout id=realtabcontent is a child of a FrameLayout.”

    But the FrameLayout with id realtabcontent is the child of a LinearLayout. The FrameLayout above it is a sibling, and I can’t figure out anything that it is used for.

    Am I missing something?

     
  21. Kevin

    April 2, 2012 at 05:22

    Hi, this is a great post, thank you. For some reason, I’ve had a lot of trouble understanding fragments, and your post definitely helped. I’m running into two problems, and I’m wondering if you might have had the same issues, and how you may have fixed them?

    First, of my tabs contain a number of EditText fields. When I change the value of an EditText on TAB1, switch to TAB2, and then switch back to TAB1, the value of the EditText has been reset. I’m guessing that I just have to store the values in onSaveInstanceState. I much preferred the TabActivity which would do all of this for you. Am I missing something?

    Second, if I start a new activity from one of my tab Fragments, and then go back to the existing FragmentActivity, then the tab content disappears. I was originally having this issue when using a TabActivity, which is why I spent the time to convert everything to Fragments. Do you know why this may be happening, and how to fix it?

    I’d appreciate any help. Thanks!

     
  22. Jason

    April 5, 2012 at 04:51

    Tried to set this up and am getting this error
    Caused by: java.lang.NullPointerException
    at com.onespeed.test.TestFragmentActivity.initialiseTabHost(TestFragmentActivity.java:91)

    On the mTabHost.setup() line

    /**
    * Step 2: Setup TabHost
    */
    private void initialiseTabHost(Bundle args) {
    mTabHost = (TabHost) findViewById(android.R.id.tabhost);
    mTabHost.setup();

     
  23. Nerijus

    April 13, 2012 at 09:36

    Nice tutorial really helpful. But there is a problem if i want to navigate inside these fragemnts.
    Problem explained:

    For an example Fragment A and B would be under Tab 1 and Fragment C and D under Tab 2. When the app is started Fragment A is shown and Tab 1 is selected. Then Fragment A might be replaced with Fragment B. When Tab 2 is selected Fragment C should be displayed. If Tab 1 is then selected Fragment B should once again be displayed. At this point it should be possible to use the back button to show Fragment A.

    Maybe some one had made this going ?

     
    • ranjith

      June 5, 2013 at 07:09

      hi Nerijus.. did u got the answer… then pls share the idea… or tutorial…. am also struggling with this problem..

       
  24. MikeW

    April 14, 2012 at 03:13

    anyone have an answer for the Type mismatch: cannot convert from Object to TabsFragmentActivity.TabInfo error?

     
    • Al

      April 29, 2012 at 15:31

      Cast it tp TabInfo

       
    • Sandeep

      May 23, 2012 at 01:39

      Eclipse suggests to type cast it. That seems to solve the error.

       
  25. justin

    April 17, 2012 at 17:00

    Mitch,
    Really awesome tutorial but I ran into a ClassNotFoundException and after reviewing and re-reviewing and determining it wasn’t the code I found this (http://stackoverflow.com/a/9831061) which tells you to make sure that android-support-v4.jar is checked and on the top of the Order and Export tab of the Java Build Path dialog. Both of though steps are required.

     
  26. anammari

    April 27, 2012 at 19:06

    in the onTabChange call back why dont you use the replace method instead of add method ft.replace(R.id.realtabcontent, newTab.fragment, newTab.tag); and not detching the current one ??

     
  27. afchin

    May 6, 2012 at 03:38

    Hey, Mitch!
    Thanks for a tutorial. I have a question, though: how do I handle saving the state of each tab? Right now, I have tabs 1,2,3. In tab 2, the default fragment is A, and I open a fragment B on top of it. If I switch to tab 3, then back to tab 2, I see A again. How do I get the tabhost to show the saved state of each tab (so that I can see B)?

    Thanks!

     
    • ranjith

      June 5, 2013 at 07:10

      did u solve it…..

       
  28. Waseem

    May 15, 2012 at 18:20

    Screenshots are always useful =)

     
  29. Arvind

    June 28, 2012 at 23:15

    Thank you for the above tutorial and your github code!! Very helpful.

     
  30. Kostas

    July 1, 2012 at 17:58

    Thank you, very helpful tutorial on Tabs and Fragments!

     
  31. Prabakaran G

    July 6, 2012 at 08:48

    Nice post, very useful android beginners.

     
  32. Sam

    July 17, 2012 at 15:13

    Hi i have used you’r sample code, can you tell me how can i bring the tab bar to the bottom of the screen

     
  33. feelingtheblanks

    July 19, 2012 at 00:08

    Do you know How would one, that followed your tutorial, stop a fragment (tab) which contains a list view from re-populating its list view after the tab’s changed and resumed over and over ? I tried overriding onResume() but no help..

     
    • mitchwongho

      July 19, 2012 at 09:43

      Hi,

      You’ll need to manage the Activity/Fragment lifecycle as prescribed here. You may need to change where the data provider is updating the adapter.
      Alternatively, you can add android:configChanges=”orientation” to the activity, if you want Android to manage the state of the activity.

       
      • feelingtheblanks

        July 19, 2012 at 18:48

        Thank you, will look into docs.

         
      • feelingtheblanks

        July 19, 2012 at 21:22

        In case sb else needs it : I managed to handle the re-populating issue by extending ListFragment and then calling ListFragment.setListAdapter(adapter) instead of Fragment but i think it now underperforms or i did sth wrong..

         
  34. h4uw1n3

    July 20, 2012 at 20:58

    Hello Mitch,

    is there any example to query data from sqlite in Tab1Fragment?
    i try to access my database… i’ve searched in google, but didn’t found any useful article… or maybe i don’t get their article….

     
    • mitchwongho

      July 20, 2012 at 21:03

      Great question.
      I haven’t worked with SQLite before. Have you had a read through Vogella’s tutorial?

       
    • h4uw1n3

      July 20, 2012 at 22:48

      thanks first for the answer… yeah… i did… he used “ListView” on the class extends…. but because im unable to requery using the cursor…. i made my own… using “Activity”… i’m new on android actually… just few month ago i start to learn java… is that possible i make another class using “activity” and return the value from sqlite or “View” to Tab1Fragment?

       
    • Vinicius de Paula (@viniciusdepaula)

      July 20, 2013 at 21:25

      @h4uw1n3, did you get any tutorial about ” sqlite in Tab1Fragment”?

       
      • mitchwongho

        July 20, 2013 at 21:48

        Vinicius & h4uw1n3,

        Since your message, I’ve had the opportunity to work with SQLite on an app with fragments. I don’t see anything out of the ordinary that is different to using SQLite in an Activity

         
  35. harbor

    August 5, 2012 at 19:09

    I like how you said you did everything when you just copied everything from the sdk demo examples.

     
  36. mike

    August 8, 2012 at 09:44

    epic code sample thak you !

     
  37. mike

    August 9, 2012 at 10:22

    Hi can i ask something though.I modified your code a bit so that i can add an icon on the tabs.When i wrote it in your downloaded code it worked when i copy-pasted the same code in my project nothing happened! do you know what could be the problem?My thoughts are that there is a problem and cannot define somehow the .xml path but i got no mistakes when running it it justs ignores it that’s how i did it : .setIndicator(“Tab 1″,getResources().getDrawable(R.drawable.icon1))
    Do you have any ideas?

     
  38. mike

    August 9, 2012 at 12:00

    Well i hate that i’m spamming but i tried this :
    .setIndicator(“″,getResources().getDrawable(R.drawable.icon1))
    and no the icon is shown but i can’t have text could it be the android version i’m developping? its api 14..looking forward for your response

     
  39. Jack Sanko

    August 16, 2012 at 15:37

    dear mitchwongho,

    I checkout your code but it is not working.

    https://github.com/mitchwongho/Andy

     
  40. mikemackintosh

    September 5, 2012 at 23:47

    Love your tutorial. Came in handy and was exactly what i needed! Thank you

     
  41. Robi Tanzil

    September 21, 2012 at 11:58

    Thanks a lot :)

     
  42. honey hong

    October 8, 2012 at 10:08

    Hey, thank you for your codes. I would like to ask, i tried to open a class that extends Activity instead of Fragment (in Tab2Fragment) when a tab is clicked, but I cant seem to open a class that extends Activity successfully. Is it because it has to be something that has to do with Fragment such as ListFragment. I am new, and if I could get some explanation, that would be great. Thanks. :)

     
  43. max

    October 8, 2012 at 16:27

    Is there a way to put the tabs at the bottom?

     
    • honey hong

      December 2, 2012 at 10:31

      Max : try android:layout_alignParentBottom = “true” at your TabWidget in your XML Layout file. It worked for me.

       
  44. DaveD

    October 10, 2012 at 22:52

    OK. I think I follow this. What I dont get is why we are checking if the fragment already exists and detaching it if it does? Why wouldnt we want to re-use the fragment if it already exists?

     
  45. boondaburra

    October 12, 2012 at 14:41

    Hello,
    Thank you for the tutorial!

    where can I add a XML style to every tab I need?

     
  46. honey hong

    November 2, 2012 at 10:28

    thanks for the codes. they are great. i would like to ask, how can i use a custom layout using your codes?

     
  47. ex0ns

    December 12, 2012 at 23:11

    This is a REALLY nice tutorial !
    But, how can I pass data to my tab from the FragmentActivity ? (using .setArguments for example)

     
  48. Madhan

    January 3, 2013 at 13:56

    Tutorial is nice. . My FirstTab contains gridview images from webservice call,when we switch over to next tab and come again images started to reload. . How to save the tabs state. . . And one More thing i need to write onitemclicklistener to the firsttab fragment class. . . is it possible to ve nested fragment in the fragment class if so how?

     
  49. alex

    January 8, 2013 at 14:43

    Thank you very much for the tutorial.

    But i have one problem: how can i switch to another tab using code (dynamically)?

    Thank you!

     
    • mitchwongho

      January 8, 2013 at 15:11

      Hi Alex,

      If you have a reference to the ViewPager, you can call ViewPager.setCurrentItem( int item )
      see: http://developer.android.com/reference/android/support/v4/view/ViewPager.html#setCurrentItem(int)

       
      • alex

        January 9, 2013 at 02:16

        Hi,

        first of all – thanks again :)

        But i don’t have da ViewPager – my code looks almost exactly like the one from the tutorial. What is working is, if i call from one of the tabs:

        Activity a = getActivity();
        if(a instanceof Start){
        ((Start) a).onTabChanged(“Tab2″);
        }

        But this way, the tab opens, but the action bar still is on Tab1. That results in an unclickable Tab1 – i have to select Tab2 first, then Tab1 is clickable again.

        I hope you can help me – this is for an exam of my studies…

         
  50. navya

    January 11, 2013 at 07:57

    thanq verymuch , its a useful example..

     
  51. DsSoft

    January 22, 2013 at 05:23

    Dear Andy,
    I add the following in Tab2Fragment.OnCreateView to get edittext in Tab1Fragment

    ……..
    View view = (LinearLayout) inflater.inflate(R.layout.tab_frag2_layout,
    container, false);
    Button button = (Button) view.findViewById(R.id.btnCalculate);
    button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
    // TODO Auto-generated method stub
    // TODO Auto-generated method stub
    FragmentActivity activity = getActivity();
    if(activity == null){
    Log.d(“Tab2″, “activity == null”);
    return;
    }
    Fragment fragment = activity.getSupportFragmentManager()
    .findFragmentByTag(“Tab1″);
    if (fragment == null)
    Log.d(“Tab2″, “fragment == null”);
    else {

    EditText edtText = (EditText) fragment.getView().findViewById(
    R.id.edtMonthlySalary);

    String text = edtText.getText().toString();
    Log.d(“Tab2″, text);
    }

    }
    });
    return view;
    ……..

    I got correct fragment, but it return null for fragment.getView()…

    Please Advise.

     
  52. Joe

    January 26, 2013 at 17:11

    Thanks a lot, that was a great help!

     
  53. khawar

    January 30, 2013 at 20:04

    Hi,

    TabActivity tabMap = (TabActivity) getParent();
    tabMap.getTabHost().setCurrentTab(3);

    I want to do the same with fragmentActivity having tabs filled with fragments..
    (sorry if I missed this part)

    thanks.

     
  54. khawar

    January 30, 2013 at 20:24

    Hi,
    How can I achieve this in fragmentactivity

    TabActivity tabMap = (TabActivity) getParent();
    tabMap.getTabHost().setCurrentTab(1);

    thanks..

     
  55. KaZzchang

    February 8, 2013 at 16:12

    Hi!

    Thx a bunch for this great tut!

    But … as some other have requested before me it would really be a great help if you would elaborate a little on how to costumize the look of the tabs. It’s driving me crazy :) An example maybe!?

    Found a method using:
    private static View createTabView(final Context context, final String text) {
    View view = LayoutInflater.from(context).inflate(R.layout.tab_custom_layout, null);
    TextView tv = (TextView) view.findViewById(R.id.tabsText);
    tv.setText(text);
    return view;

    Could this somehow be incorporated into your code?

    Thanks again!

     
    • khawar

      February 18, 2013 at 06:06

      set your indicator like this..

      tabview = createTabView(mTabHost.getContext(), “FAQ’s”, R.drawable.faq);
      MainTabActivity.addTab(this, this.mTabHost,
      this.mTabHost.newTabSpec(“FAQ’s”).setIndicator(tabview),tabInfo = new TabInfo(“FAQ’s”, Frag_FAQs.class, args)));

      // createTabView
      private static View createTabView(final Context context, final String text, int img) {
      View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
      ImageView image = (ImageView) view.findViewById(id.tabs_img);
      image.setImageResource(img);
      TextView tv = (TextView) view.findViewById(R.id.tabsText);
      tv.setText(text);
      return view;
      }

       
  56. sash

    February 19, 2013 at 08:35

    Thank you!!! great post it is and it had helped me a lot… :)

     
  57. Kalyan

    February 19, 2013 at 11:00

    Man U Simply Rock!!!!! Thanks a lot this helped me finish my project!!!!! Thank You So Much!!! Keep Goin!!!:):)

     
  58. kamal

    February 21, 2013 at 09:00

    hiiiii mitchwongho

    Can you help me …. I want to add icons on the tab .. How I can do this

     
  59. aditlal90

    March 2, 2013 at 02:10

    I have one Activity -MAIN.java , where i have a listview and each click jumps to TabFragmentActivity.java but i want to pass data with it so that i can dynamically change textview in the 3 tabs how to do it

     
  60. samz

    March 7, 2013 at 16:26

    Thank you great post. I used the setArgument method to pass argument to fragment,but i’m getting an exception “frament already active”, if you can help me on how to fix this issue would great, following is a code that i used to pass the arguments..

    private class TabInfo {
    private String tag;

    private Class clss;

    private Bundle args;

    TabInfo(String tag, Class clazz, Bundle args) {
    this.tag = tag;
    this.clss = clazz;
    this.args = args;
    }

    }

    private static void addTab(AppMajikTabActivity activity, TabHost tabHost, TabHost.TabSpec tabSpec, TabInfo tabInfo) {
    // Attach a Tab view factory to the spec
    tabSpec.setContent(activity.new TabFactory(activity));
    String tag = tabSpec.getTag();

    // 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.
    tabInfo.fragment = activity.getSupportFragmentManager().findFragmentByTag(tag);
    if (tabInfo.fragment != null && !tabInfo.fragment.isDetached()) {
    FragmentTransaction ft = activity.getSupportFragmentManager().beginTransaction();
    //this checking for stop fragment already added exception.
    if(!tabInfo.fragment.isAdded()){
    tabInfo.fragment.setArguments(null);
    tabInfo.fragment.setArguments(tabInfo.args);
    }
    ft.detach(tabInfo.fragment);
    ft.commit();
    activity.getSupportFragmentManager().executePendingTransactions();
    }

    tabHost.addTab(tabSpec);
    }

    .MyActivity.addTab(this, this.mTabHost,
    this.mTabHost.newTabSpec(tabSpecTag).setIndicator(view),
    //setIndicator(ApplicationConstants.EMPTY_STRING,tabIndicator),
    (tabInfo = new TabInfo(tabInfoTag, claz, bundle)));
    this.mapTabInfo.put(tabInfo.tag, tabInfo);

     
  61. Ranjith

    March 11, 2013 at 13:41

    hi

    i cant able to set 3 fragements inside one tab using Listviews in 3 fragements …. so any one send me a sample code for the multiple fragements inside one tab using listview in each fragement…:):)

     
  62. Channa

    March 20, 2013 at 12:18

    Great tutorial, thanks!

     
  63. prashant

    April 5, 2013 at 07:28

    Thanks for this great work….! I am using your code but stucked at a point how to get a menu in this mainActivity..? please give some idea….
    Thanks…

     
  64. Bru No

    April 11, 2013 at 10:39

    Hey Mitch nice article very helpful.
    Do you know if it’s possible to refresh TabFragmentX when touching (or clicking) the selected tab? I mean when a tab is selected, on every touch/click on the selected tab how to refresh/reload the related TabFragmentX? Thanks

     
  65. Barry

    April 19, 2013 at 16:35

    Hi, i am wondering if it is possible to load FragmentActivities into the tabs instead of Fragments? It doesnt matter in my app if the Parent Activity that holds the TabHost is a FragmentActivity. I simply need to load in FragmentActivities into the tabs.

    Thanks and great tutorial.

     
    • mitchwongho

      April 20, 2013 at 10:39

      Only fragments. What are you trying to achieve?

       
  66. sash

    April 30, 2013 at 11:49

    please tell me how to make tab 2.x looks like tab 3.x

     
  67. Piovezan

    May 8, 2013 at 02:10

    Hi, thank you very much for the tutorial, it is great!
    I had a hard time making TabHost support vertical tabs though, at least using Compatibility library v4. I only wish Android had a simpler way of achieving this.

     
  68. wendy

    May 13, 2013 at 16:29

    Thanks alots for your code, it’s help me alots..i have try on your code but i unable to get focus when i try to type on the edittext inside the tab fragment, anyone have any ideas?

     
  69. James

    May 14, 2013 at 04:58

    Great tutorial, but have you had any trouble using this Android 4.2.2? It worked great, but now I’m testing on 4.2.2 and the tabs disappeared.

     
  70. ranjith

    May 23, 2013 at 12:55

    how pass a bundle to my Tab1Fragment

     
    • mitchwongho

      May 27, 2013 at 00:42

      Generally, you set Fragment arguments using Fragment.setArguments( Bundle bundle)

       
      • ranjith

        June 5, 2013 at 07:29

        thnx dear

         
  71. sara

    May 29, 2013 at 07:43

    thanks for great Blog
    my question is how i show tab bar on Child activity
    i want to achieve this

     
    • mitchwongho

      May 30, 2013 at 22:32

      Hi Sara,

      I would recommend following the Android design guideline whereby the tab bar is persistant in the UI described here

       
  72. Blake

    May 30, 2013 at 21:29

    Hi there! I could have sworn I’ve been to this blog before but after checking through some of the post I realized it’s new to
    me. Nonetheless, I’m definitely glad I found it and I’ll be bookmarking and checking back frequently!

     
  73. ranjith

    June 5, 2013 at 06:36

    when i press on a button on the fragment1 i need to open another fragment fragment2 under the same tab. and on back press i need to come back to fragment1. how we can implement this any tutorial

     
  74. Steven

    June 10, 2013 at 19:32

    Hey Mitch, I really like your tutorial/explanation of fragment tabs. Thanks for putting this up! I followed it exactly but seem to be having one problem still that I hope you could help me with.

    When I run the FragementActivity the default tabs layout does not get loaded, and when I try to switch tabs I get an error saying the Activity ‘cannot be cast to android.support.v4.app.Fragment’.

    This is the line(s) that the error points to; (in onTabChanged)

    newTab.fragment = Fragment.instantiate(this, newTab.clss.getName(), newTab.args);
    ft.add(R.id.realtabcontent, newTab.fragment, newTab.tag);

    Any help with this would be greatly appreciated!

    Thanks in advance,
    Steven

     
    • stevenschemers

      June 15, 2013 at 23:46

      Hey Mitch, I was able to figure out my problem with casting to the support library. I did not import the support library in my fragments.

      Now everything looks fine, and my fragmentActivity and fragments don’t have any errors/warnings but when I switch between tabs I never see any of the fragments show up..

      Any help with this would be awesome! I’ve been stuck on this for a couple days.

      Thanks in advance,
      Steven

       
      • stevenschemers

        June 16, 2013 at 01:46

        Nevermind, I figure it out.. The realtabcontent frame was set to 0dp so i was never able to see the loaded fragment.

         
  75. Dennis

    June 28, 2013 at 16:00

    This is some great code. Thanks Mitch, helped a lot!

     
  76. shinkyoshin

    July 2, 2013 at 10:14

    Everything is very open with a clear clarification of the challenges.
    It was truly informative. Your site is useful.
    Many thanks for sharing!

     
  77. Drikus

    July 17, 2013 at 11:01

    Hey Mitch, this is fantastic, your tabs works and is a great replacement for my initial deprecated use of tabs. Would you mind helping with 1 addition to your code please?, can you please advise how i would be able to change the tabs based on an listview onclick item.

    I’ve added the below code to TabsFragmentActivity.java class, and my listview is populate as well with the below values. The problem is , as it stands now, each onclick generates a new activity, and was hoping there is a way just to update the tabs within the same activity with each listitem value click..


    ListView mlistView = (ListView) findViewById(R.id.mainListView);
    mlistView.setAdapter(new ArrayAdapter(this,
    R.layout.subcategory_listview_text,
    new String[] {“Simple”, “Simon”, “Says”, “You”, “Need”,
    “to”, “Click”, “here”, “NOW”}));

    mlistView.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView parent, View view,
    int position, long id) {
    // When clicked, show a toast with the TextView text Game, Help, Home
    Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
    Toast.LENGTH_SHORT).show();
    String sText = ((TextView) view).getText().toString();
    Intent intent = null;

    if(sText.equals(“Simple”))
    intent = new Intent(getBaseContext(),
    SubCategories_simple.class);

    else if(sText.equals(“Simon”))
    intent = new Intent(getBaseContext(),
    SubCategories_simon.class);
    else if(sText.equals(“Says”))
    intent = new Intent(getBaseContext(),
    SubCategories_says.class);
    else if(sText.equals(“You”))
    intent = new Intent(getBaseContext(),
    SubCategories_you.class);
    else if(sText.equals(“Need”))
    intent = new Intent(getBaseContext(),
    SubCategories_need.class);
    else if(sText.equals(“To”))
    intent = new Intent(getBaseContext(),
    SubCategories_to.class);
    else if(sText.equals(“Click”))
    intent = new Intent(getBaseContext(),
    SubCategories_click.class);
    else if(sText.equals(“Here”))
    intent = new Intent(getBaseContext(),
    SubCategories_here.class);
    else if(sText.equals(“Now”))
    intent = new Intent(getBaseContext(),
    SubCategories_now.class);
    if(intent != null)
    startActivity(intent);
    }
    });

    Thx a bunch

     
  78. Vinicius de Paula (@viniciusdepaula)

    July 20, 2013 at 19:45

    Gr8 tuto bruh! Tks a lot 4 share it!

     
  79. Raj Bhardwaj

    July 26, 2013 at 10:50

    Hi,

    Thanks for great tutorial. I have a question.
    Question: As you have described earlier that If I have a button on tab1 fragment and then I can set onClick event listener to that button as

    LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
    // Register for the Button.OnClick event
    Button b = (Button)theLayout.findViewById(R.id.btn_startActivity);
    b.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v)
    {
    Toast.makeText(Tab1Fragment.this.getActivity(), “OnClickMe button clicked”, Toast.LENGTH_LONG).show();
    }
    });
    return theLayout;
    //return (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
    }

    Now lets suppose If I want to start a new activity when this button is clicked, and I want to have tabs on my new created activities then How can I achieve this. please give piece of code to understand better.

     
  80. Shanka Nuwan

    August 8, 2013 at 13:23

    nice idea, sample code is not works for me. could u please check that again, i’m using android developer tool

     
  81. Guillaume

    August 9, 2013 at 19:43

    Nice job! I’m using the framework ActionBarSherlock to be retrocompatible, but basicaly I do the same than you.

    I have a question ;
    How can I manage persistent view hierarchy when you change from tab1 to tab2 and back to tab1?

    I tried ; onSaveInstanceState and onRestoreInstanceState but I don’t know how to save the hierarchy view into the Bundle (putAll seems not to do the job), anyway does i have to implement this on FragmentActivity class or on Fragment(s) classes?
    I tried ; onStop for Fragment instead of detach…
    I tried ; setRetainInstance and getRetainInstance before detach Fragment(s)… nope
    I tried ; saveFragmentInstanceState before detach but how do I get the Fragment state back after attach the fragment again?

    It gets me nuts!

     
  82. Nikita Gurwani

    August 12, 2013 at 14:41

    is dis deprecated?

     
    • Guillaume

      August 14, 2013 at 14:43

      @Nikita, did you asked me? why should onSaveInstanceState deprecated?
      No. It never called…

       
      • mitchwongho

        August 17, 2013 at 23:46

        @Nikita @Guillaume I’ve pushed a fix to git that resolves the NPE

         
  83. Guillaume

    August 14, 2013 at 10:58

    onSaveInstanceState is never called for Fragment…

     
  84. Carol

    August 27, 2013 at 04:32

    Great information. It is helping me a lot to get started. Question from a newbie…. Where is the com.andy.R coming from?

     
  85. anu

    August 29, 2013 at 14:36

    What is followed by ‘implements’ ? it is missing

     
  86. brk

    August 31, 2013 at 06:16

    i have 5 tab, my tab titles are long length like “MyTab1″,”MyTab2″,”MyTab3″,”MyTab4″,”MyTab5″

    but tab1, tab2, tab3’s title’s last letter down bottom of tab. but tab4 and tab5 are normal… pls help me? or can you say to me how i put icon for tab title

     
  87. viveknandhanreddy

    August 31, 2013 at 11:44

    i am getiing error can anyone plz help me

    newTab.fragment = Fragment.instantiate(this, newTab.clss.getName(), newTab.args);

    Type mismatch: cannot convert from android.app.Fragment to android.support.v4.app.Fragment

     
  88. Mani

    September 12, 2013 at 09:27

    hi all,

    i have a problem after using this code, that when i switch the tabs, my tabs contains adapters, so after switching the data is still there so adapters only calls notifyDataSetChange, so it does not me any data, cause i am not setting adapter again, how can i fix this issue, that with the same older data i show the things to user,

    Kindly help me on this ASAP.

     
  89. Jainendra Agarwal

    September 25, 2013 at 03:19

    how to use EditText widget in Tabfragments. When I type anything in the EditText, I am not able to type and the corresponding tab fragment is highlighted in which the EditText widget is.

     
    • Jainendra Agarwal

      September 27, 2013 at 00:49

      NOTICED THAT THIS PROBLEM IS IN EMULATOR ONLY. On mobile it runs fine. Any solution for emulator problem

       
  90. jazz11

    September 26, 2013 at 16:51

    Hey, very nice tutorial really helped me.
    One question I have, what if I want to place tabs at the bottom of the screen (like Iphone) how to do it?

     
  91. DeepakBhatt

    October 4, 2013 at 13:25

    how to change bottom border of all tabs,. default color is blue and i want it to be yellow, the bottom border and the selected item border both to be changed, how to apply these changes.

    Thanks in advance

     
  92. devika

    October 16, 2013 at 08:31

    Thank you so much for the post a very useful and informative.

     
  93. Heather

    October 18, 2013 at 08:23

    “Android : Tabs. The Fragment Way | I Should Write This
    $#!T Down” actually makes me ponder a tiny bit further.

    I appreciated every single component of this post. Thanks for your effort ,Matthew

     
  94. Merlijn

    October 18, 2013 at 23:35

    Hi, I have used your tutorial code in my own app, but I had to rewrite the code so I could understand what really is going on in the code. Is there are possibility you update the code in your github repository? I will be more than happy to share my re-written code so that others understand your code better :-)
    Just let me know…

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 38 other followers

%d bloggers like this: