Requirements: Android: Tabs. The Fragment Way
Requirements: Android: Tabs. The Fragment Way
T Down
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
The Code
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.
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 1/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
<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>
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).
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)
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 2/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
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
*/
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);
}
}
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 =
this.mapTabInfo.put(tabInfo.tag, tabInfo);
TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab 2"), ( tabInfo =
this.mapTabInfo.put(tabInfo.tag, tabInfo);
TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab 3"), ( tabInfo =
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.
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 3/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
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();
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.
mLastTab = newTab;
ft.commit();
this.getSupportFragmentManager().executePendingTransactions();
}
}
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
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 4/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
*
*/
public class TabsFragmentActivity extends FragmentActivity implements TabHost.OnTabChangeListener {
/**
* @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 =
this.mapTabInfo.put(tabInfo.tag, tabInfo);
TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab2").setIndicator("Tab 2"), ( tabInfo =
this.mapTabInfo.put(tabInfo.tag, tabInfo);
TabsFragmentActivity.addTab(this, this.mTabHost, this.mTabHost.newTabSpec("Tab3").setIndicator("Tab 3"), ( tabInfo =
this.mapTabInfo.put(tabInfo.tag, tabInfo);
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 5/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
// 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();
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
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 6/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Summary
TODO
150 Comments
Posted by mitchwongho on October 4, 2011 in Android
Pingback: Android : Page Swiping using ViewPager « I Should Write This $#!T Down
Pingback: Android : Tabs + ViewPager (Swipe-able Tabs, FTW) « I Should Write This $#!T Down
Benoit
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
Reply
mitchwongho
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 7/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Hi Antonio,
I encourage you to get the source from Github, then you’ll have all the sample code.
Reply
Ben W
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
https://github.com/mitchwongho/Andy.git
ofir
Hey,
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.
Reply
mitchwongho
If I were to add a button to Fragmenthaving the id @+id/frag1_button, then you can register for button click events
as follows:
@Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGT
}
});
return theLayout;
}
}
Reply
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 8/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Thanks for asking this question and thanks for the reply. It really helped me.
kiduxa
ofir
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
Reply
Gaurav
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
It is possible to independently update the fragments in a TabView via the FragmentManager or TabHost
Reply
ghouse
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
Reply
mitchwongho
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
Hi mitchwongho
if fragments with in fragments is not possible then how can we implement a tabview like contacts in any android phone
ranjith
if u got the answer for what ghouse asked.. then pls share i am struggling with the same doubt…
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 9/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Shane
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?
Reply
mitchwongho
Hi,
Reply
ramiz
Much appreciated.
Reply
atc
Reply
Mark
Reply
Alex
It is possible to provide a link to Github, where we can find all code?, I have some missunderstands…
Reply
larry
Thank you for putting this together. I dropped your code into Eclipse and get 1 error:
from eclipse:
Reply
Prabakaran G
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 10/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
you can typecast it, like this.
Reply
Renaud FAVIER
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 !
Reply
Sohne Mann
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?
Reply
memmers
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?
Reply
Alex
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:
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
Reply
Max
Hi,
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 11/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Type mismatch: cannot convert from Object to TabsFragmentActivity.TabInfo
Reply
Twinkle
Solution A:
Type cast to TabInfo:
TabInfo newTab = (TabInfo)this.mapTabInfo.get(tag);
Reply
Eugenia Gabrielov
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!
Reply
sandhya
Tab1
Tab2
Fragment4->Fragment6
Tab3
Reply
khawar
@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
yaa i almost find out an answer… but am not sure is it right or not. but it is working…
in fragment1 u have a button click or list view onclick listener. so on the onClick function. u write the below code.
Reply
Brian
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 12/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
March 22, 2012 at 17:57
Hi, thanks for posting this. I wanted to point out something what seems to be a mistake:
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?
Reply
Kevin
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?
Reply
Jason
/**
* Step 2: Setup TabHost
*/
private void initialiseTabHost(Bundle args) {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
Reply
Nerijus
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.
Reply
ranjith
hi Nerijus.. did u got the answer… then pls share the idea… or tutorial…. am also struggling with this problem..
Reply
MikeW
anyone have an answer for the Type mismatch: cannot convert from Object to TabsFragmentActivity.TabInfo error?
Reply
Al
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 13/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
April 29, 2012 at 15:31
Cast it tp TabInfo
Reply
Sandeep
Eclipse suggests to type cast it. That seems to solve the error.
Reply
justin
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.
Reply
anammari
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
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!
Reply
ranjith
Reply
Waseem
Reply
Pingback: Unable to Start Activity Error using Tabs | PHP Developer Resource
Pingback: How to implement listview & nested layouts in tabbed layout on Android
Arvind
Thank you for the above tutorial and your github code!! Very helpful.
Reply
Kostas
Reply
Prabakaran G
Reply
Sam
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
Checkout http://stackoverflow.com/questions/5014002/how-to-set-tab-bar-at-the-bottom
Reply
feelingtheblanks
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..
Reply
mitchwongho
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
feelingtheblanks
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..
h4uw1n3
Hello Mitch,
Reply
mitchwongho
Great question.
I haven’t worked with SQLite before. Have you had a read through Vogella’s tutorial?
Reply
h4uw1n3
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?
Reply
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 15/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Reply
mitchwongho
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
I like how you said you did everything when you just copied everything from the sdk demo examples.
Reply
mike
Reply
mike
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?
Reply
mike
Reply
Jack Sanko
dear mitchwongho,
Reply
mikemackintosh
Love your tutorial. Came in handy and was exactly what i needed! Thank you
Reply
Thanks a lot
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 16/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Reply
honey hong
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.
Reply
max
Reply
honey hong
Max : try android:layout_alignParentBottom = “true” at your TabWidget in your XML Layout file. It worked for me.
Reply
DaveD
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?
Reply
boondaburra
Hello,
Thank you for the tutorial!
Reply
honey hong
thanks for the codes. they are great. i would like to ask, how can i use a custom layout using your codes?
Reply
ex0ns
Reply
Madhan
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?
Reply
Pingback: Unable to instantiate acticity component info: I fail at following tutorials video
Pingback: Following android tab tutorial, can’t find or launch installed app on device or emulator video
Pingback: Following android tab tutorial, can't find or launch installed app on device or emulator : Android Community - For Application Development
alex
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 17/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
But i have one problem: how can i switch to another tab using code (dynamically)?
Thank you!
Reply
mitchwongho
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
Hi,
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.
navya
Reply
DsSoft
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 {
}
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 18/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
}
});
return view;
……..
Please Advise.
Reply
Pingback: Android Tabs with List View : Android Community - For Application Development
Joe
Reply
Pingback: how to implement Fragment tab into a Fragment layout? : Android Community - For Application Development
khawar
Hi,
I want to do the same with fragmentActivity having tabs filled with fragments..
(sorry if I missed this part)
thanks.
Reply
khawar
Hi,
How can I achieve this in fragmentactivity
thanks..
Reply
Pingback: how to replace tabhost, actvitygroup and child activities with fragments : Android Community - For Application Development
KaZzchang
Hi!
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!?
Thanks again!
Reply
khawar
// 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;
}
Reply
sash
Reply
Kalyan
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 Development
kamal
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 Development
aditlal90
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
Reply
samz
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 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();
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 20/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
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
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…:):)
Reply
Channa
Reply
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
Reply
mitchwongho
Reply
Barry
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.
Reply
mitchwongho
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 21/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
April 20, 2013 at 10:39
Reply
sash
please tell me how to make tab 2.x looks like tab 3.x
Reply
mitchwongho
Reply
Reply
wendy
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
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
Reply
mitchwongho
Reply
ranjith
thnx dear
sara
Reply
mitchwongho
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 22/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
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
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!
Reply
mitchwongho
Thanks, Blake!
Reply
ranjith
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
Reply
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)
Thanks in advance,
Steven
Reply
stevenschemers
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
Reply
stevenschemers
Nevermind, I figure it out.. The realtabcontent frame was set to 0dp so i was never able to see the loaded fragment.
Dennis
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 23/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
This is some great code. Thanks Mitch, helped a lot!
Reply
shinkyoshin
Reply
Drikus
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
Reply
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 24/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Gr8 tuto bruh! Tks a lot 4 share it!
Reply
Raj Bhardwaj
Hi,
@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.
Reply
Pingback: Binary App Dev: Apps | how to keep tabs visible on every activity
Shanka Nuwan
nice idea, sample code is not works for me. could u please check that again, i’m using android developer tool
Reply
Guillaume
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!
Reply
Nikita Gurwani
is dis deprecated?
Reply
Guillaume
Reply
mitchwongho
@Nikita @Guillaume I’ve pushed a fix to git that resolves the NPE
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 25/26
09/09/13 Android : Tabs. The Fragment Way | I Should Write This $#!T Down
Guillaume
Reply
Carol
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
Reply
brk
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
Reply
thepseudocoder.wordpress.com/2011/10/04/android-tabs-the-fragment-way/ 26/26