26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#! T Down thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 1/26 I Should Write This $#!T Down CLOSE ENCOUNTERS OF THE CODE KIND 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 (http://android- developers.blogspot.com/2011/09/preparing-for-handsets.html) ). 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 (http://developer.android.com/guide/topics/ui/actionbar.html) 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 (http://developer.android.com/sdk/compatibility-library.html) 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.

Android _ Tabs

Embed Size (px)

Citation preview

Page 1: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 1/26

I Should Write This $#!T Down

CLOSE ENCOUNTERS OF THE CODE KIND

Android : Tabs. The Fragment Way

04 OCTIf 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 willensure your app is compatible with pre-Honeycomb, Honeycomb and Ice Cream Sandwich (tablet and phone) OS versions (see this article (http://android-developers.blogspot.com/2011/09/preparing-for-handsets.html)). Remember, in Android 2.x Tabs are presented as classic “filing” tabs, while on Android 3.xand higher tabs are represented in the ActionBar (http://developer.android.com/guide/topics/ui/actionbar.html) 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(http://developer.android.com/sdk/compatibility-library.html) library. In my example, I’m using Compatibility library v4

Step-by-Step

1. Define TabHost layout2. Define Tab fragment layouts3. Define Tab fragments4. 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’llnotice that the FrameLayout id=realtabcontent is a child of a FrameLayout. Isn’t this redundant? The answer is no, be attaching out fragments to thisFrameLayout.

Page 2: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 2/26

<?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-aloneactivity. 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 fortheir 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 mainFragmentActivity 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)

Page 3: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 3/26

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 ofActivity.

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, weinitialise 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 firsttab 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 ofTabFactory (TabFactory is an inner class that extends TabContentFactory that creates an empty View as a placeholder for our fragments). Next, we detachthe Fragement associated with the tab we’re trying to add. Then, finally we add the TabSpec to the TabHost.

Page 4: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 4/26

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. WhenonTabChanged(…) 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 storedin 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 clickedthe 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 FrameLayoutid=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

Page 5: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 5/26

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

Page 6: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 6/26

// 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

Page 7: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 7/26

<?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

150 CommentsPosted by mitchwongho on October 4, 2011 in Android

Tags: Android, Fragments, TabHost, Tabs, UI

150 Responses to Android : Tabs. The Fragment Way

Pingback: Android : Page Swiping using ViewPager « I Should Write This $#!T DownPingback: Android : Tabs + ViewPager (Swipe-able Tabs, FTW) « I Should Write This $#!T DownBenoit

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

Reply

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?

Reply

mitchwongho

December 20, 2011 at 21:49

About these ads (http://en.wordpress.com/about-these-ads/)

Page 8: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 8/26

Hi Antonio,

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

Reply

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?

mitchwongho

June 27, 2012 at 09:53

https://github.com/mitchwongho/Andy.git

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 befound inside the TabsFragmentActivity class, which is very nasty thing to do… putting all the functions that handle the UI events of each tab content insidethe 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 theTabsFragmentActivity class?

Thanks in advance.

Reply

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

Reply

Page 9: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 9/26

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!! =)

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?

Reply

Stalski

December 31, 2011 at 15:32

Great post for starters like me

Reply

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.

Reply

mitchwongho

January 18, 2012 at 15:48

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

Reply

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 thesame tab how can i do that one

Reply

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.

Reply

ghouse

February 1, 2012 at 13:32

Hi mitchwonghoif 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…

Page 10: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 10/26

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 gradientor image. Where would I do that?

Reply

mitchwongho

January 18, 2012 at 16:15

Hi,

You’ll want to look at stylising the TabWidget view http://developer.android.com/reference/android/widget/TabWidget.html

Reply

ramiz

January 20, 2012 at 11:25

This is great. Very simple and easy to understand.

Much appreciated.

Reply

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

Reply

Mark

March 5, 2012 at 18:52

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

Reply

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…

Reply

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/tabsfragmentline 130 Java Problem

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

Any ideas? Thanks!

Reply

Prabakaran G

July 6, 2012 at 08:52

Page 11: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 11/26

you can typecast it, like this.

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

Reply

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’tsee 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 !

Reply

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?

Reply

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 iconsto each fragment? is this something that should be done from xml or from the java code directly?

thanks for your help

Reply

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 soon….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?

Reply

rui_helder

January 25, 2013 at 19:32

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

Reply

Max

March 8, 2012 at 02:03

Hi,

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

Page 12: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 12/26

Type mismatch: cannot convert from Object to TabsFragmentActivity.TabInfo

Did someone manage to fix it ?

Reply

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

Reply

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 otherongoing projects!

Reply

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??

Reply

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

Reply

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……

Reply

Brian

Page 13: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 13/26

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 isused for.

Am I missing something?

Reply

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 twoproblems, 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, thevalue 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 woulddo 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 wasoriginally 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 behappening, and how to fix it?

I’d appreciate any help. Thanks!

Reply

Jason

April 5, 2012 at 04:51

Tried to set this up and am getting this errorCaused by: java.lang.NullPointerExceptionat 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();

Reply

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 isselected. 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 FragmentB 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 ?

Reply

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..

Reply

MikeW

April 14, 2012 at 03:13

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

Reply

Al

Page 14: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 14/26

April 29, 2012 at 15:31

Cast it tp TabInfo

Reply

Sandeep

May 23, 2012 at 01:39

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

Reply

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 theJava Build Path dialog. Both of though steps are required.

Reply

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 ??

Reply

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 isA, 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 (sothat I can see B)?

Thanks!

Reply

ranjith

June 5, 2013 at 07:10

did u solve it…..

Reply

Waseem

May 15, 2012 at 18:20

Screenshots are always useful =)

Reply

Pingback: Unable to Start Activity Error using Tabs | PHP Developer ResourcePingback: How to implement listview & nested layouts in tabbed layout on AndroidArvind

June 28, 2012 at 23:15

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

Reply

Kostas

July 1, 2012 at 17:58

Thank you, very helpful tutorial on Tabs and Fragments!

Reply

Prabakaran G

July 6, 2012 at 08:48

Page 15: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 15/26

Nice post, very useful android beginners.

Reply

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

Reply

mitchwongho

July 17, 2012 at 15:47

Checkout http://stackoverflow.com/questions/5014002/how-to-set-tab-bar-at-the-bottom

Reply

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’schanged and resumed over and over ? I tried overriding onResume() but no help..

Reply

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.

Reply

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 callingListFragment.setListAdapter(adapter) instead of Fragment but i think it now underperforms or i did sth wrong..

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….

Reply

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?

Reply

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 myown… 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?

Reply

Page 16: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 16/26

Vinicius de Paula (@viniciusdepaula)

July 20, 2013 at 21:25

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

Reply

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 differentto using SQLite in an Activity

Pingback: Android : Tabs. The Fragment Way « Another Cornerharbor

August 5, 2012 at 19:09

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

Reply

mike

August 8, 2012 at 09:44

epic code sample thak you !

Reply

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 icopy-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 cannotdefine somehow the .xml path but i got no mistakes when running it it justs ignores it that’s how i did it : .setIndicator(“Tab1″,getResources().getDrawable(R.drawable.icon1))Do you have any ideas?

Reply

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

Reply

Jack Sanko

August 16, 2012 at 15:37

dear mitchwongho,

I checkout your code but it is not working.https://github.com/mitchwongho/Andy

Reply

mikemackintosh

September 5, 2012 at 23:47

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

Reply

Pingback: Handle state of Fragment | Jisku.com - Developers NetworkPingback: Handle state of Fragment | Free Android EnthusiastsRobi Tanzil

September 21, 2012 at 11:58

Thanks a lot

Page 17: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 17/26

Reply

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. Iam new, and if I could get some explanation, that would be great. Thanks.

Reply

max

October 8, 2012 at 16:27

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

Reply

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.

Reply

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-usethe fragment if it already exists?

Reply

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?

Reply

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?

Reply

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)

Reply

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 inthe fragment class if so how?

Reply

Pingback: Unable to instantiate acticity component info: I fail at following tutorials videoPingback: Following android tab tutorial, can’t find or launch installed app on device or emulator videoPingback: Following android tab tutorial, can't find or launch installed app on device or emulator : Android Community - For Application Developmentalex

January 8, 2013 at 14:43

Thank you very much for the tutorial.

Page 18: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 18/26

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

Thank you!

Reply

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)

Reply

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 clickableagain.

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

navya

January 11, 2013 at 07:57

thanq verymuch , its a useful example..

Reply

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() {

@Overridepublic void onClick(View v) {// TODO Auto-generated method stub// TODO Auto-generated method stubFragmentActivity 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);}

}

Page 19: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 19/26

}});return view;……..

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

Please Advise.

Reply

Pingback: Android Tabs with List View : Android Community - For Application DevelopmentJoe

January 26, 2013 at 17:11

Thanks a lot, that was a great help!

Reply

Pingback: how to implement Fragment tab into a Fragment layout? : Android Community - For Application Developmentkhawar

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.

Reply

khawar

January 30, 2013 at 20:24

Hi,How can I achieve this in fragmentactivity

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

thanks..

Reply

Pingback: how to replace tabhost, actvitygroup and child activities with fragments : Android Community - For Application DevelopmentKaZzchang

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’sdriving 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!

Reply

khawar

February 18, 2013 at 06:06

set your indicator like this..

tabview = createTabView(mTabHost.getContext(), “FAQ’s”, R.drawable.faq);

Page 20: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 20/26

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

// createTabViewprivate 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;}

Reply

sash

February 19, 2013 at 08:35

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

Reply

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!!!:):)

Reply

Pingback: How to set the content of tabhost to a fragment : Android Community - For Application Developmentkamal

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

Reply

Pingback: How to save/Restore state of Views of fragment on Tab change : Android Community - For Application Developmentaditlal90

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 candynamically change textview in the 3 tabs how to do it

Reply

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 helpme 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 spectabSpec.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.

Page 21: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 21/26

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

Reply

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 onetab using listview in each fragement…:):)

Reply

Channa

March 20, 2013 at 12:18

Great tutorial, thanks!

Reply

Pingback: Android Fragment, No view found for id inside TabHost | BlogoSferaprashant

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…

Reply

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 theselected tab how to refresh/reload the related TabFragmentX? Thanks

Reply

mitchwongho

April 20, 2013 at 10:35

Try adding a OnTabChangeListerner to TabHost

Reply

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 holdsthe TabHost is a FragmentActivity. I simply need to load in FragmentActivities into the tabs.

Thanks and great tutorial.

Reply

mitchwongho

Page 22: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 22/26

April 20, 2013 at 10:39

Only fragments. What are you trying to achieve?

Reply

sash

April 30, 2013 at 11:49

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

Reply

mitchwongho

May 1, 2013 at 01:43

Something like ViewPageindicator?

Reply

Pingback: (SOLVED) New layouts in tabHost Android | BlogoSferaPiovezan

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 achievingthis.

Reply

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?

Reply

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.

Reply

ranjith

May 23, 2013 at 12:55

how pass a bundle to my Tab1Fragment

Reply

mitchwongho

May 27, 2013 at 00:42

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

Reply

ranjith

June 5, 2013 at 07:29

thnx dear

sara

May 29, 2013 at 07:43

thanks for great Blogmy question is how i show tab bar on Child activityi want to achieve this

Reply

mitchwongho

Page 23: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 23/26

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

Reply

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 tome. Nonetheless, I’m definitely glad I found it and I’ll be bookmarking and checking back frequently!

Reply

mitchwongho

May 30, 2013 at 22:38

Thanks, Blake!

Reply

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 tofragment1. how we can implement this any tutorial

Reply

Pingback: Switch between fragments not indicated in the tabhost | BlogoSferaSteven

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 stillthat 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 castto 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

Reply

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 ofthe fragments show up..

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

Thanks in advance,Steven

Reply

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.

Dennis

June 28, 2013 at 16:00

Page 24: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 24/26

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

Reply

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!

Reply

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 toyour 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, HomeToast.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

Reply

Vinicius de Paula (@viniciusdepaula)

July 20, 2013 at 19:45

Page 25: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 25/26

Gr8 tuto bruh! Tks a lot 4 share it!

Reply

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 eventButton b = (Button)theLayout.findViewById(R.id.btn_startActivity);b.setOnClickListener(new View.OnClickListener() {

@Overridepublic 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 achievethis. please give piece of code to understand better.

Reply

Pingback: Binary App Dev: Apps | how to keep tabs visible on every activityShanka 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

Reply

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)… nopeI tried ; saveFragmentInstanceState before detach but how do I get the Fragment state back after attach the fragment again?…It gets me nuts!

Reply

Nikita Gurwani

August 12, 2013 at 14:41

is dis deprecated?

Reply

Guillaume

August 14, 2013 at 14:43

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

Reply

mitchwongho

August 17, 2013 at 23:46

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

Page 26: Android _ Tabs

09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down

thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 26/26

Guillaume

August 14, 2013 at 10:58

onSaveInstanceState is never called for Fragment…

Reply

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?

Reply

anu

August 29, 2013 at 14:36

What is followed by ‘implements’ ? it is missing

Reply

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

Reply

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

Reply

Blog at WordPress.com. The Choco Theme.

Entries (RSS) and Comments (RSS)