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