united-coders

TwitterFacebookGoogleRSS
  • Home
  • Authors
    • Christian Harms
    • Nico Heid
  • Newsletter
Home » Use Android ActivityGroup within TabHost to show different Activity

Use Android ActivityGroup within TabHost to show different Activity

Posted on September 30, 2010 by Nico Heid Posted in Uncategorized 40 Comments

android

there is an updated version to this article with some improvements. please also read: Android ViewFlipper within TabHost for Tabs with different Views … and better memory footprint.

When you’re using a TabHost each tab has it’s own Activity. Now image you want to change the Activity for a certain tab. If you just go on and create a new Activity and display it, your Tab Layout is no longer visible.

For that reason you need a ActivityGroup within the Tab where you want to change the Activity.
An ActivityGroup is:

A screen that contains and runs multiple embedded activities.

Let's look at this at a real life example. An Android app that shows your podcasts. In the first Activity you get to see all podcasts by subscription. If you touch the subscription, you see the single podcasts you've downloaded for that subscription.

The Tabhost contains three tabs, one for the MediaPlayer, one for the archive and one for available downloads.
        TabHost tabHost = getTabHost();

        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Player").setContent(
                new Intent(this, PlayerActivity.class)));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Archive").setContent(
                new Intent(this, ArchiveGroup.class)));
        tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("Updates").setContent(
                new Intent(this, DownloadList.class)));

The ArchiveGroup takes care which Activity is shown in the second tab. With setContentView you can bring the View to the front.

        View view = getLocalActivityManager().startActivity("ArchiveActivity", 
                new Intent(this, ArchiveActivity.class).addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();

        setContentView(view);

Now all you need to do is to bring another View to the front after an action is triggered. In this case, after a ListItem is clicked.

        String album = (String) getListView().getItemAtPosition(position);
        Intent intent = new Intent(getApplicationContext(), ArchiveAlbums.class);
        intent.putExtra("album", album);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        View view = ArchiveGroup.group.getLocalActivityManager().startActivity("ShowPodcasts", intent).getDecorView();

        ArchiveGroup.group.setContentView(view);

You need to tell the ActivityGroup which view is to be on top and set the appropriate Flag, so that the View will be on top.

Of course now you have to keep track which activity is in front, how they behave and what happens if the back button is pressed. But that gives you room for customizing the behavior.

The full code can be found on github in the GpodRoid project.

Another good tutorials are by H. Larsen and Eric Harlow.

  • Bio
  • Latest Posts
My Google+ profile

Nico Heid

I work as a software engineer during the day and sometimes hack a bit in my free time. That currently includes anything from software, system and networks to raspberry pi and hardware. You can find most of my results on this blog.

Latest posts by Nico Heid (see all)

  • A scalable, affordable WordPress hosting, lessons learned - May 19, 2013
  • Code Jam – Candy Splitting - March 30, 2013
  • Manually concatenating two wave files - March 16, 2013
android
« Google code jam solution for alien numbers
Javascript Functional programming with Underscore or ECMAScript5 »

40 thoughts on “Use Android ActivityGroup within TabHost to show different Activity”

  1. Twitter Trackbacks for Use Android ActivityGroup within Tab says:
    September 30, 2010 at 12:50

    [...] Use Android ActivityGroup within TabHost to show different Activity | unitedcoderscom.appspot.com unitedcoderscom.appspot.com/nico-heid/use-android-activitygroup-within-tabhost-to-show-different-activity – view page – cached When you’re using a TabHost each tab has it’s own Activity. Now image you want to change the Activity for a certain tab. If you just go on and create a new Activity and display it, your Tab Layout is no longer visible. Tweets about this link [...]

  2. Mark Murphy says:
    September 30, 2010 at 14:08

    Pop open hierarchyviewer on your app sometime. Having activities-in-tabs, let alone activity-groups-in-tabs, chews up a lot of stack space, represented in hierarchyviewer as additional depth in your view hierarchy. Using your technique, developers are increased risk of OutOfStackExceptions. It also requires more code than simply having views-in-tabs, uses more heap space than simply having views-in-tabs, etc. Any UI that can be represented by activities-in-tabs can be implemented as views-in-tabs.

    Even navigation within a tab can be done simply via a ViewFlipper as the container. And, since ViewFlipper lets you remove things (unlike ActivityGroup, AFAICT), you have better memory management control this way.

  3. Nico Heid says:
    September 30, 2010 at 19:40

    i will look into it.

  4. Anonymous says:
    September 30, 2010 at 21:56

    Hi,

    I have tabhost with multiple activities, in first activity i have button when i click this button, i need to display second activity without loosing my tabhost and header, once i get my second activity in this also i have 2 button when i click first button, it should go back to my first activity and when i click second button it should go back to third activity. i did coding using the following

    Intent activityCurrentSummaryIntent = new Intent(v.getContext(), 
                                                     currentsummary.class);
    activityCurrentSummaryIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    				
    View view = ArchiveGroup.group.getLocalActivityManager().startActivity(
                    "ShowPodcasts",  
                    activityCurrentSummaryIntent).getDecorView();
    ArchiveGroup.group.setContentView(view);
    
    // or 
    
    replaceContentView("currentsummary", activityCurrentSummaryIntent);
    
    public void replaceContentView(String id, Intent newIntent) {
      LocalActivityManager mLocalActivityManager = getLocalActivityManager();
      View view = mLocalActivityManager.startActivity(id,newIntent.addFlags(
                              Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
      this.setContentView(view);
    }     
    

    when i click button i am getting stopped unexpectedly error. Could you please suggest solution for this as early as possible,

    Thanking you in advance

    WIth Regards,
    Roy

  5. Nico Heid says:
    October 1, 2010 at 10:04

    you have a working example for that?

  6. Android ViewFlipper within TabHost for Tabs with different V says:
    October 16, 2010 at 16:46

    [...] article is a follow up of Use Android ActivityGroup within TabHost to show different Activity. As you probably noticed or read in the comments, the provided solution in the last article was [...]

  7. JBM says:
    November 19, 2010 at 19:00

    Hi Nico,
    The ArchiveGrop tab with different activities is real nice. How can we go back to the first view in the tab, after launching the second activity from the List View? — Basically, if I clck on the back button, the whole application closes….. Any idea. Thanks

  8. Matt Ingram says:
    November 19, 2010 at 21:20

    how would you go about starting an activity, for instance i wanna take photos from an action off an activity in the group, but i want the camera to have full screen, not be constricted to inside the tabs? any ideas?

    thanks,
    matt

  9. Nico Heid says:
    November 21, 2010 at 13:52

    just start the cam as new activity. it will be full screen then.
    i added an example in the demo, you can find it here: https://github.com/nheid/unitedcoders-android

  10. Nico Heid says:
    November 21, 2010 at 14:26

    if you see the back button, do your own magic. e.g. going to the specific tab and don’t send it to the superclass via super.onKeyDown.
    Like this:

     public boolean onKeyDown(int keyCode, KeyEvent event) {
            if ((keyCode == KeyEvent.KEYCODE_BACK)) {
                  // do your magic
               }
    

    Just make sure you apply it the way, a user would expect the behavior to be. Go back to the previous screen or leave the application when appropriate.

  11. Stephane says:
    December 24, 2010 at 14:52

    Hi,

    I use the same code as you, but i have an exception. I don’t know why!
    EXCEPTION : Unable to start activity ComponentInfo {intent to start name} android.view.WindowManager$BadTokerException: Unable to add window — token android.app.local

    Does anyone have any idea please?

    Thanks

  12. Tarun Aggarwal says:
    March 4, 2011 at 14:46

    Hello all,

    I have divided my android screen in two parts in one part i put my own app and in second part i want to insert a tab host, widget and it needs to extend my main class but the main class is already extended to some activity used by my first app. Is there any way to extend my main class by any other method ? Can anyone please help me in this ??

    any kinda help would be appreciated !!

  13. Sumant says:
    March 16, 2011 at 12:39

    Thnx for this great post.
    But mw having few q’s

    1)TabBar is present in my activity.The first tab is having an Button “submit”. After click on submit is should go to second tab i.e. that ta should get opened.
    Now in this what is mentioned is that after click on button the content of the next activity is displayed on the current activity but i want that after click on button it should move to the next tab.

    i want to move the tab and not it’s content also i want tab bar should present there.
    Thanx for any help……………….

  14. Nico Heid says:
    March 16, 2011 at 22:16

    if i understand your button does some magic. is it starting an activity?

    if the button should switch the tab, you have to switch tabs in the eventhandler
    see: http://developer.android.com/reference/android/widget/TabHost.html#setCurrentTab(int)

  15. Nico Heid says:
    March 16, 2011 at 22:18

    i can’t follow you.
    maybe draw a sketch or refer to some code, please?

  16. Nico Heid says:
    March 16, 2011 at 22:20

    there’s a discussion about it here:
    http://stackoverflow.com/questions/1561803/android-progressdialog-show-crashes-with-getapplicationcontext

    seems specific to api version or how your current context is.

  17. Sumant says:
    March 17, 2011 at 13:36

    Hi, thnx for reply.

    I have tried this before but it is not working it is giving null pointer exception.

    Also regarding button magic onclick of button i have started another activity.

    My first tab is set by using tabHost.setCurrentTab(0) i.e. tab 0 is selected.

    Now Tab 0 is having button after click on button tab1 should got selected.

    tabs.java is my activity which extends Tab Activity. tab 0 is having activity1 ,tab1 is having activity2 & so on…..
    after click on button it is showing the next activity on current activity with same tab is selected not the one which is holding that activity

  18. Sumant says:
    March 25, 2011 at 09:00

    Hi,
    Now i am able to get the next activity call on current activity in tabbar and it work fine.As mention in above tutorial.
    But after click on tab i want to replace the next view which i am displaying on current view should replace with older view.
    E.g.tab1 ,tab2,tab3.After click on tab1 it should open the activity which is specified in tabactivity.

    Thanks in advance for any help suggestion…

  19. sambit says:
    May 4, 2011 at 10:52

    This tutorial is real very help full.
    I have tired is implement the same in my project but I m facing problem.
    Onclicking on the CityActivity I am starting the ShowCity Activity,in which i am givivng some user input but after setResult() my parent onActivityresult is not getting called.
    Any solution of how to get the result back from a activity.

  20. Mike says:
    June 28, 2011 at 16:54

    i was trying to do your implementation somehow i can;t execute it? do you have the code for this example?

  21. Nico Heid says:
    June 29, 2011 at 14:42

    the project moved, so the link was dead.
    I corrected it.

    you can jump directly to a activity with a tabhost here:
    https://github.com/gpodder/GpodRoid/blob/master/src/com/unitedcoders/android/gpodroid/activity/PodcastManager.java

    nico

  22. Joe says:
    July 6, 2011 at 06:09

    Thanks very much~~~~~

    Finally solve my problem!

  23. zekt0r says:
    July 11, 2011 at 14:04

    I have the same problem. How can you solve?

  24. Himanshu says:
    July 12, 2011 at 11:02

    Hey I have 2 tabs. So i have the main activity and two more activities for the 2 tabs. The first tab(activity) has a listview. What i want is when i click on a item in the list a new activity starts in the same tab. The java file containing the listview extends ListActivity. Now if i follow ur tutorial to start a new activity the class should extend ActivityGroup. If i make the java file containing the listview extend to ActivityGroup instead of ListActivity then it gives error in the setListAdapter() and getListView() functions. Can u please help me with this?

  25. Anonymous says:
    August 16, 2011 at 15:15

    tabhost problem

  26. venkatakumar says:
    August 19, 2011 at 05:58

    The tutorials looking good i want to display a map in on of the tab. can u tell me the code.

  27. Manish says:
    August 25, 2011 at 06:43

    Hi,
    I have use the same approach to develop an app where I have 3 tabs and each tab has its own ActivityGroup. I have menus for each activity. But when I press menu button, the menu does not appear. After doing some random trails I found that If I implement onCreateOptionsMenu in ActivityGroup then only menu appears. I am not able to execute onCreateOptionsMenu of Activity.
    Please suggest how to use menu of Activity as I have many activities in single ActivityGroup and by implementing onCreateOptionsMenu in ActivityGroup is not the right way to handle this problem.

    Thanks.

  28. Kenny says:
    September 2, 2011 at 18:27

    This was a tremendous help! I do have one issue tough. Tab1 onCreate launches Activity1. Clicking on a list item in Activity1 will launch Activity2. Clicking on a list item in Activity 2 launches Activity3. If I hit the back button on Activity3, it goes back to Activity1 closing Activity3 and Activity2. I want it to show Activity2, rather than closing 2 activities at once. Does anybody else have this problem?

    Thanks in advance.

    - Kenny

  29. Amit Saha says:
    September 21, 2011 at 07:09

    I have tabhost with five activities. Each activity has four child activity. when I enter in the child activity I did not go back to the main activity in the tabHost.

    Please help to resolv this problem.

  30. Anonymous says:
    October 10, 2011 at 10:50

    In the above code ArchiveGroup.group is not working error appeared at that place in the below replaceContentview is working but am require the ArchveGroup.group is required.please give the suggestion.

  31. Sundar says:
    October 25, 2011 at 07:11

    In this iam getting TabHost error.could me send me a program to my mail-id for tab layout without any errors??

  32. Nikhil says:
    November 25, 2011 at 09:04

    Hi,
    I tut is good to know… but now I want to refresh the view in activitygroup everytime it is loaded or comes on front.
    How can I do that
    Please reply.
    Its urgent
    Nikhil

  33. Nikhil says:
    November 25, 2011 at 09:08

    Hi,
    I tut is good to know… but now I want to refresh the view in activitygroup everytime it is loaded or comes on front.
    How can I do that
    Please reply.
    Its urgent
    Nikhil

  34. Yatibawri says:
    January 6, 2012 at 09:14

    Hi,
    I have four tabs under TabActivity.Say 1, 2, 3, 4
    I go on 1st tab then 2nd then 3rd and now if i want to go back to the
    last pressed tab then wat shud i do for that.
    I tried many other options using Activity group but all finishes the application .

    Please if you can help me out..
    Thanks

  35. Anonymous says:
    February 21, 2012 at 23:29

    I have a page showing some data with Spinner activity and a listview activity. On selection of Spinner item I populate listview item, onclick of the listview item I show some description in a separate Activity. I have tabs in my page. To get tabs on the listview selection activity I created a ListviewGroup acvity and followed the code specified here.

    Now when I select an item in the spinner I am getting an error and the log cat error is this:
    02-21 16:27:41.149: ERROR/AndroidRuntime(858): android.view.WindowManager$BadTokenException: Unable to add window — token android.app.LocalActivityManager$LocalActivityRecord@40520218 is not valid; is your activity running?

    02-21 16:27:41.149: ERROR/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)

    Can someone help me here.. Thanks

  36. lijun says:
    February 26, 2012 at 01:39

    thanks very much !

    View view = ArchiveGroup.group.getLocalActivityManager().startActivity(“ShowPodcasts”, intent).getDecorView();

    ArchiveGroup.group.setContentView(view);

    but what is “group”? why the “group” is not defined in my code and need to creat ??

  37. Sayan says:
    March 9, 2012 at 12:11

    Even I’m facing the same problem. If you have a working example can you please forward it my mail address.

  38. Sayan says:
    March 9, 2012 at 12:14

    If you have a working example for switch between activities on button click within the tab-host without loosing tab & Header, can you please forward it my mail address??

  39. james says:
    April 24, 2013 at 06:13

    I have some problem to ask, please.
    I’m tried listview in this framework code.
    I have A subActivity and B subActivity.
    A subactivity have a list, when i click listview’s item, it will change to B subActivity.
    It’s correct.
    when i click back key in B subActivity, It is change back A subActivity.
    But the A subActivity can’t click item ,first.
    It’s have to drag up or drag down with listview,then click item just to affect.
    Have any one have this problem? how to solve this problem?
    thank you very much.

  40. hardik says:
    April 28, 2013 at 07:19

    i have three tabs in tab activity ,i used activity group as you mention above, every things works fine but i want to move first child of particular tab when same tab click, in 1st tab i have three childs activites and my current selected child activity is third now when i click on same tab i want to move to the first child activity of the tab. how i achive this?

Leave a comment Cancel reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Tags

android code jam code puzzle hackercup hosting java javascript permutations project euler python server

Recent Comments

  • garcinia cambogia walmart on Free IP to Geo Location script
  • Yoda Conditions | Pack 6 – Palo Alto on What are yoda conditions?
  • Nico Heid on The art of escaping
  • hardik on Use Android ActivityGroup within TabHost to show different Activity
  • james on Use Android ActivityGroup within TabHost to show different Activity

Recent Posts

  • A scalable, affordable WordPress hosting, lessons learned
  • google code jam 2013 – tic-tac-toe-Tomek solution
  • Google code jam 2013 – the lawnmower
  • code puzzles and permutations
  • Code Jam – Candy Splitting

Meta

  • Log in
  • Entries RSS
  • Comments RSS
  • WordPress.org

Copyright

Creative Commons License
This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
© united-coders
  • there is an updated version to this article with some improvements. please also read: Android ViewFlipper wi