Android Tabs with Fragments

Evelina Vrabie

Dedicated coder, occasional blogger, hackathon goer and friendly team mate.

You may also read...

  • http://- flagg327

    Thank you so much! it works just fine. Great job. Thank you.

  • aditya

    what is R.id.bar and R.layout.list_item….its not working

  • Pingback: android fragment apk | Full APK Updates for You!()

  • http://coopr8.com/ Gabriel S. Dilday

    I’m amazed, I must say. Rarely do I come across a blog that’s both
    equally educative and amusing, and let me tell you, you have hit
    the nail on the head. The problem is an issue that too few people are speaking intelligently
    about. Now i’m very happy I found this in my search for something regarding this.

  • http://www.androidcg.com.ar Eduardo K

    Thanks! Nice post!

  • https://www.youtube.com/watch?v=ugy4uhWOU04 Alberto

    When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get several
    emails with the same comment. Is there any way you can remove
    people from that service? Thank you!

  • Shikha Jha

    Hi,
    Thanks for the code. I need some help, i want to ask how to spread out the tabs to take the width of whole screen.Please help me.What kind of code i need to add in it. Please help me. Please reply as early as possible . Thank you.

  • http://www.androprogrammer.com wasim

    Confused with the code. you have explained well.
    And how you have used those red and green color for rows ?
    I like the style …

  • Willem Ghijsen

    Nevermind. I played around with it, and the strings are called from strings.xml. I originally thought it was in the java code:
    public static final String TAB_WORDS = “words”;
    public static final String TAB_NUMBERS = “numbers”;
    but that was incorrect

  • Willem Ghijsen

    I was going through the code, and added an extra tab to experiment. This was successful, however, I cannot seem to find out how/why the tabs start with a capital letter, since the strings passed in are all lowercase. Does anyone know why this happens?

  • http://www.mahmoud-khedher.com mahmoud khedher

    thx for this tutorial !but i have a question !!
    how to hide the titles of the tabs !
    need your help !

  • k40s

    Thanks a lot for this

  • Pingback: Passing data to a Fragment in part of a tabbed FragmentActivity after coming back from another startActivityForResult() | Technology & Programming Answers()

  • John

    Very useful. Thanks

  • Pingback: Android实战技术:类iOSTab和Header - 移动端开发 - 开发者()

  • Pingback: Passing data to a Fragment in part of a tabbed FragmentActivity after coming back from another startActivityForResult(CopyQuery CopyQuery | Question & Answer Tool for your Technical Queries,CopyQuery, ejjuit, query, copyquery, copyquery.com, android d()

  • bahaha

    Can you please post the entire source code? Where is r.id.bar defined, new to android here.

  • vkhooda

    Well Blog post…By the developer for the developers….:)
    Thanks for sharing good tutorial about tab in fragments.

  • Pingback: Difference Between TabHost and FragmentTabHost | BlogoSfera()

  • Tom

    Brilliant! I was looking for use of custom tabs with fragments because I wanted to use the new Navigation Drawer! Only tutorial I can find that does what I want and I’ve been looking for 3 days! A+++!

  • Zeus

    Can u pls suggest as to how can i add an onclick listener to one of the tab to open a new activity or fragment inside the same tab

  • Zeus

    What if i wanted to start a child activity form one of the tabs then would the tabs still be maintained on that child

    activity as well

  • Ankit Rohilla

    thank you for great tutorial
    Its working

  • Babar

    Hi How can i have tabs at bottom??

  • Shakir Orakzai

    wonderfull very nice

  • Pingback: Design an App which is smartphone and tablet compatible | BlogoSfera()

  • arw357

    Thx . usefull indeed !

  • rashid

    How do i implement this using ListView instead of Creating a list of LinearLayouts? Pls help.

  • mesi

    what is R.id.bar ? pls mention

  • Pingback: android tab selector | What Is()

  • Pingback: Good example for tabhost : Android Community - For Application Development()

  • http://completelybaked.blogspot.com/ Jim_Welke

    Right on, Evalina! Great code sample; it clarified a lot things I (an Android newbie) was struggling with. Specifically, how to structure the .xml files so that configuration info and selectors work right. I appreciate the clarity in your comments, too. Thanks. Peace.

  • Authman Apatira

    This project (FragmentTabs) crashes when you rotate the device 4x.

  • Pingback: Project for tabs using fragments not working video()

  • Pingback: How to make tabs using fragments (using content by factory)? : Android Community - For Application Development()

  • dereky

    it really helps me a lot,thanks very much

  • Dusan

    OMFG! Does anybody know why i cant set weight atribut on root LinearLayout in tabs.xml. I tryed a lot of thing, but it wont work… I want tabs to spread out to take whole screen…

  • Dim

    Is it simple enough to add each fragment to the backstack such that hitting the back button returns to the previous tab?

  • nate

    If you wanted to make one of the fragments a mapview how would you go about do that?

  • Everton Barros

    Very nice post, I needed to do something similar, only in my case I needed to put tabs in a popup, after picking up a bit, I managed to reach the final solution. Thank you!

  • rathael

    I think you must change “getListView().setAdapter(mAdapter);” by “setListAdapter(mAdapter);”.

  • jin

    Hi, This tutorial really helped me a lot. I want to make a third tab, but unable to code it. Pl help for the same.

  • CH4:D

    Line 106 is wrong. It should just simply be
    if (mPosition < mTotal).

    As it stands, the last element in the array won't show up if you add the "- 1" because it stops one item behind.

  • Alex

    this is crashing on second orientation change

  • binhbt

    Oh man. Thanks a lot. nice example :X:X:X:X:X:X:X:X::-*

  • zx81

    Hi, Thanx for nice example, saves lot of learning time.

    BTW, what is R.layout.tab in newTab() and how can I create a proper XML for that element?

  • seetha

    you are superb dear….

  • Filip Bulovic

    Very nice example, thanks.

  • mith

    Hi. Thanks for the wonderful code and tutorial. I have a question though. How could I make the tabs scrollable as in if I add many tabs , how to make it scrollable horizontally ?
    Thanks

    • mith

      A quick google search helped me.. This is how I did

      Hope this helps somebody.
      Thanks

    • evelyne24

      Hey, thanks for the comment. My code has become a bit obsolete because there are other people out there creating compatibility libraries to support all kinds of ICS features, including tabs, tabs + swipe, etc. Best look for Jake Wharton’s libraries (he’s the author of ActionBarSherlock). Check out this library: https://github.com/JakeWharton/Android-ViewPagerIndicator/ it probably has everything you want.

      • Thomas Markle

        You should add an update at the top of the post, I just found the ABSherlock library and it looks like it’s a great time saver.

  • http://profiles.google.com/mlaccessdev nicolas raby

    Hi, android.support.v4.app.FragmentActivity , does I mean the code requires Android v4 at least ?

  • Pingback: Android Fragments con pestañas | LiME Creative LabsLiME Creative Labs()

  • kyk

    Thanks for posting a working project!

  • Pingback: Android U_MISSING_RESOURCE_ERROR when populating a custom view in a ListFragment | PHP Developer Resource()

  • Pingback: Android Tabs with Fragments « tediscript.wordpress.com()

  • Gladiatornoida

    I found it in your code. Thanks!

  • Gladiatornoida

    private TabSpec newTab(String tag, int labelId, int tabContentId) {
    Log.d(TAG, “buildTab(): tag=” + tag);

    View indicator = LayoutInflater.from(getActivity()).inflate(
    R.id.tab,
    (ViewGroup) mRoot.findViewById(android.R.id.tabs), false);
    ((TextView) indicator.findViewById(R.id.text)).setText(labelId);

    TabSpec tabSpec = mTabHost.newTabSpec(tag);
    tabSpec.setIndicator(indicator);
    tabSpec.setContent(tabContentId);
    return tabSpec;
    }

    Can you please give explanation for R.id.tab & indicator.findViewById(R.id.text). From where these ids come?

    • http://www.facebook.com/kyle.beckman Kyle Beckman

      I have the same question…. any help?

      • Nelson

        I’m not sure about R.id.tab, but I think you actually mean android.R.id.tabs, but R.id.text is just the id of a TextView defined in the list_item.xml file. She’s not talking about it in the text, but if you download the tar file with the whole project there you can see that file, which is actually the layout for every single row displayed in the listview.

        • http://www.facebook.com/nico.sordoni Nico Sordoni

          R.id.tab doesn’t appear anywhere, but instead appear R.layout.tab, that is the layout used as “background” for the indicators of the tabs. R.id.text is a TextView inside this layout, used to contain the text of the tab’s indicator.

  • Tom Karni

    This is a greate tutorial, helped me a lot.

  • samcool

    Is there an article only for fragments ? I searched around for lot of tutorials and tried implementing by following them but couldn’t get it working. I am looking for fragment implementation which will work on all the android versions. That will be really helpful. Thank you in advance.

  • Zerotvt

    Thanks

  • Dada Venki

    hi i have read your tutorial its nice but i have a doubt if in any tab if i want to move another screen (same tab) like clicking any of the rows in listview how it can be done any suggestion will be a great help

  • ye009

    Can you post some code for listFragment with which used customlistAdapter in setAdapter and listfragment loads data from asychTaskLoader, I am having problem with how to refresh the listfragment when data is loaded from asynchTaskLoader. Please help

  • Vinesh Gaadhe

    Ohhh man u rocks… I was looking for this from last 24 hours…thanks a lot man

    • http://uk.linkedin.com/in/evelinavrabie Evelina Vrabie

      I’m a woman, but that’s fine…glad to be of help

    • http://frontiervillepardner.blogspot.com FrontierVille

      Evelina is not a man…

  • Pingback: The Android Tutorial Series Part 3 – Layout | My Experiments with Technology()

  • http://twitter.com/cloudjacker Cloud Jacker

    Thanks! I dont understand what your activity is doing though, why do the individual tabs load the words and numbers so slowly? Is that a fragment feature?

    I need to use tabs to load full layouts. Ie tab 1 loads an activity and tab 2 loads a separate activity! But TabActivity and that entire methodology is deprecated, yet this fragment “replacement” isn’t very intuitive for froyo+

    • Evelina Vrabie

      Have you read the code? The words are loaded slowly because I wanted to simulate an operation that takes time, like a network call. If you actually read the code you’ll see there’s a Thread.sleep() that does the trick (there’s a comment that says that as well).

      About the methodology, if you think it’s deprecated then use something else that you see fit. If you find a better way, please share so we can all learn

  • Abe Froman

    When I try running the code you provided I just get a loading icon that never goes away. The done loading string appears in my LogCat but nothing is appearing on the screen. If you have any ideas what I may have done wrong please let me know.

    • Brill Pappin

      Run it through the debugger, that’s that it’s for.
      I had to modify it as well for my project, but it works just fine.

      • Tom Karni

        I had the same problem when I used it in my project but not when I ran this package. Brill, how did you solve it?

    • U Sargin

      i have used android-support-v13 no v4 and i have same problem

      • Tom Karni

        I finally solved it with:
        @Override
        public void onLoadFinished(Loader loader, Void result) {
        //update adapter

        setListShown(true);
        }

        • CH4:D

          God, this really solved my issue as well! I’ve been up all night trying to customize this tutorial to suit my needs but even simple label and id adjustments screw this app up.

          I don’t know if this is an android or eclipse bug but i tried tracking the changes little by little and rerunning at each change.

          It appears that if you add one extra tab to the tabs_fragment.xml the whole application gets foobar’d. However, this may not be the exact cause but probably a consequence because the issue is intermittent.

          Sometimes the loading screen shows up even if you undo the changes and uninstall the app. Sometimes it just corrects itself after a few runs.

        • rathael

          Try to change “getListView().setAdapter(mAdapter);” by “setListAdapter(mAdapter);”.

  • Brill Pappin

    Here is anther tip. The tab in your example are left aligned.
    if you add the android:layout_weight=”1″ attribute to the root LinierLayout of tabs.xml they will spread out to take up the whole width of the screen.

    Long labels will still cause some tabs to be longer than others, but that would be an issue no matter what you did.

    It was also easy to add an image to the tabs.xml so that you get a more “iphone” like effect.

    • http://www.facebook.com/thanhbinh.gd Thanh Binh Bui

      Thank you. i love u :-*

    • Kiko

      About the labels problem, when you add android:layout_weight=”1″ attribute, also set the android:layout_width=”0dp” and tabs will have same width

    • G3eak

      Tnx

    • Ankit Rohilla

      Thank you sir

    • Tom

      Brilliant! Tab layout weight was just what I was looking for!

  • Brill Pappin

    Best example of Tabs with Fragments i’ve seen yet. A simple as can be and the code is clean and obvious.

  • tabbykitten

    Thanks for tips
    tab_1, tab_2 is overhead for tabhost_fragment.xml is overhead, you can use android.R.id.tabcontent directly

  • Vinh Bui

    Thanks a lot, it’s really useful to me.

  • http://profiles.google.com/wp19831014 peng wang

    thanks,it is help me .

  • Evelina Vrabie

    Glad to help

  • Jalota_arun

    Thnx alot…this exact i have been lokking for last 3 days…!!gr8 post thnk u!!!

    • nargis

      Thanks ..good tutorial..modified it to add icons ,tab selectors and a third tab too

      • kunal

        its not working

    • G3eak

      Same… best what i have found so far and also simple to understand for beginner, Thanks. =)