Skip to Content

Tabs With Intents

If you look at the Android widgets and classes related to tabs, you'll see that a tab can have either a View or an Activity as its contents. Most of the time, people use Views, as they are simpler to implement and lighter-weight to run. However, there may be circumstances where you feel putting your activities in tabs would be useful, so let's take a look at how that is done, in a modified excerpt from Version 1.9 of The Busy Coder's Guide to Android Development.

If you want to use an Activity as the content of a tab, you provide an Intent that will launch the desired Activity; Android's tab-management framework will then pour the Activity's user interface into the tab. So, let's create a tabbed Web browser.

Your natural instinct might be to use an http: Uri as the target of the Intents, one Intent per tab. That way, you could use the built-in Browser application and get all of the features that it offers. Alas, this does not work. It appears you cannot host other applications' activities in your tabs, only your own activities, presumably for security reasons.

But, we can always use the WebView widget to provide a simplified browsing experience.

Here is the source to the main activity, the one hosting the TabView:

[sourcecode language="java"]
public class IntentTabDemo extends TabActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

TabHost host=getTabHost();

host.addTab(host.newTabSpec("one")
.setIndicator("CW")
.setContent(new Intent(this, CWBrowser.class)));
host.addTab(host.newTabSpec("two")
.setIndicator("Android")
.setContent(new Intent(this, AndroidBrowser.class)));
}
}
[/sourcecode]

As you can see, we are using TabActivity as the base class, and so we do not need our own layout XML — TabActivity supplies it for us. All we do is get access to the TabHost and add two tabs, each specifying an Intent that directly refers to another class. In this case, our two tabs will host a CWBrowser and an AndroidBrowser, respectively.

Those latter two activities are simple wrappers around WebView:

[sourcecode language="java"]
public class CWBrowser extends Activity {
WebView browser;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

browser=new WebView(this);
setContentView(browser);
browser.loadUrl("http://commonsware.com");
}
}
[/sourcecode]

[sourcecode language="java"]
public class AndroidBrowser extends Activity {
WebView browser;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);

browser=new WebView(this);
setContentView(browser);
browser.loadUrl("http://code.google.com/android");
}
}
[/sourcecode]

They simply load a different URL into the browser: the CommonsWare home page in one, the Android home page in the other.

The resulting UI shows what tabbed browsing could look like on Android:

Using distinct subclasses for each targeted page is rather wasteful. Instead, we could have packaged the URL to open as an "extra" in an Intent and used that Intent to spawn a general-purpose BrowserTab activity, which would read the URL out of the Intent "extra" and use this. The proof of this is left as an exercise for the reader.

Might We Suggest...

  • Too Many Bits for DDMS
    If you're like me, you do your Android development outside Eclipse and therefore rely upon the full range of the Android toolkit, from activitycreator through DDMS. And, if you're like me, you just pl...

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

28 Responses to “Tabs With Intents” Leave a reply ›

  • This site ranks one of the better information resorces I have registered for!!!! Thanks Jeff @ 411 Realty,Inc.

  • Thanks alot.. I was looking for this.

  • One more question.
    Say I have a tab called A
    I have an activity displayed on it on Tab A

    How do i display a new activity on Tab A without leaving the tab View?

    i.e. How do I launch a new activity within the current Tab?

  • @haden: I'm not sure that's possible.

  • It's a real shame.Android should have provided a method of launching activities within a tab.Thanks anyway

  • IN RESPONSE TO THE ABOVE:

    YES, sure its very possible.

    Instead of
    this.startActvity(...)
    use
    this.getLocalActivityManager().startActivity(...)

  • I can't seem to run that code... nor any code similar to that for that matter...

    Can anyone confirm this code still works for the SDK v1.1?

  • This is a test comment.

  • This comment was tried with FireFox.

  • @r45k:

    The code worked for me a week or two ago on the 1.1r1 SDK.

    Visit the CommonsWare site and download the source code to my book. You'll find the above code in a complete project (Activities/IntentTabs). Try that and see if it works for you.

    If not, join the [cw-android] Google Group and post your symptoms, and I can look into the problem.

  • didn't work for me either

    no compiler errors but when i run in the emulator i get the following error message:

    "The application Tabs with Intents (process com.android.test) has stopped unexpectedly. Please try again"

    This is happening on SDK v1.1

    cheers

  • Hello Mark...

    Even I am facing the same issue... Please lemme know how to tackle it... No Compilation errors ... No Warnings... Simply.. the app fails to execute...

  • The code shown in this blog post is not ALL the code you need to run the application. For example, you need to add your two in-tab activities to your AndroidManifest.xml file.

  • Aha! My comment-posting problems seem to be when I include a URL. So, let's try a more elaborate reply...

    The code shown in this blog post is not ALL the code you need to run the application. For example, you need to add your two in-tab activities to your AndroidManifest.xml file.

    A complete version of this project can be found in the source code for my Android book -- visit http://commonsware.com/Android/ and scroll down to the Source Code link. In the ZIP file, you will find Activities/IntentTabs that contains the complete project.

  • Hello Mark...

    Thanks for the reply...

    I did download that source code and tried running the project that youve provided... it dint workout... it didnt run either... :(

  • @Sujay:

    I just ran it here, and it works just fine. I suspect there is some other problem with your environment.

  • Hello Mark;

    Reinstalled the whole environment!!!

    Problem Solved.... Thanks a lot for support...

    I am developing a downloader based app.... U have any resources to refer and you could point me to?? Would be of great Help for me...

    Regards n Best Wishes

  • @Sujay:

    Glad you got it working!

    I am not sure what a "downloader based app" is. I would recommend you post your query to the [android-developers] Google Group, anddev.org, or the Android board at JavaRanch. Be sure to describe in somewhat greater detail what it is you are trying to do or need assistance with.

  • Hello Mark;

    Thnaks for the great suggestion last time...

    Ive built the app halfway...

    Now my problem is... the user is forced to use the search feature which has been implmented using html and php ..... which further yeilds the download result and download link...

    Everything works fine untill user searches for the keywords.... but the search results are displayed in a new browser window.... and it escapes out of my actual application.
    The same happens even when i try to open a hyperlink... how do i keep the whole process contained within that tab??

    My whole aplication would require the webpage in these stages..

    1-> On Application start; it will show the search page in the search tab and allow user to search...

    2-> It must show the search results and download link within the tab.... ( Here it escapes it of the app... and opens the browser)

    3-> On clicking on the download link.... the downloader is invoked... ( Here ill be forcing my downloader function to take control)

    Currently my aim is to keep the stage 2 within the tab....
    Help will be much appreciated....

    Regards;
    Sujay

  • Hi, nice tutorial!

    I followed the example, then made one of the child activities (e.g. CWBrowser) display a dialog using showDialog(). Now if I rotate the device, the dialog disappears and is not re-created, although dialogs of the parent activity (e.g. IntentTabDemo) are re-created.

    Anyone else experiencing this problem? Any ideas on how to solve it?

  • Its not getting executred

  • Читал про это уже на каком то другом сайте, но у вас гораздо прикольней написано ;)

  • Hey Mark,

    doesnt think open the URL in a new view?

    Ive followed this and while it did infact load a page when that tab was selected, it was not in the view within the tab, it was a new window and not as show in your pics.

    Any Idea what could be causing this?

    many thanks

Leave a Reply

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>

We allow third-party companies to serve ads and/or collect certain anonymous information when you visit our web site. These companies may use non-personally identifiable information (e.g., click stream information, browser type, time and date, subject of advertisements clicked or scrolled over) during your visits to this and other Web sites in order to provide advertisements about goods and services likely to be of greater interest to you. These companies typically use a cookie or third party web beacon to collect this information. To learn more about this behavioral advertising practice or to opt-out of this type of advertising, you can visit www.networkadvertising.org.