Frank LaRosa
Frank LaRosa

Reputation: 3623

Accessing sibling tabs in an Android application?

I have an Android application using a TabHost to create several tabs with different activities in each tab.

When someone performs a certain action in the activity associated with tab A, I want to programatically switch to tab B, and call a function on tab B's activity to provide it with some data generated in tab A.

Is such a thing possible? I don't know how to access either the TabHost object or the B activity from within the A activity. I tried passing these objects in to the A activity by adding them as "extras" to the Intent, but this doesn't work, probably because the classes are not serializable. If I could access the TabActivity itself, that would probably be the best solution.

Thanks, Frank

Upvotes: 0

Views: 493

Answers (2)

Squonk
Squonk

Reputation: 48871

Implement a BroadcastReceiver in the TabActivity and another in Activity B.

Register both in the manifest with custom intent filter 'actions'

Get Activity A to send a broadcast with an Intent including extras that the TabActivity will receive.

Have the TabActivity switch tabs then send a broadcast with an Intent with extras that Activity B will receive/process.

To expand on this, think of it this way...

Under 'normal' circumstances an Activity is a stand-alone / self-contained entity. If it needs to have some action performed by another Activity, it shouldn't need to know anything about that other Activity, just a way to 'call' it, i.e., use an Intent set with the relevant action/category and extra data.

In the case of an Activity which is embedded as tab content, this mostly still applies. The Activity itself doesn't 'know' that it has been embedded as tab-content (nor should it). As such it knows nothing about the TabHost or Tabactivity (when using one). It also doesn't/shouldn't know specifically that there are other tabs with other Activities...

It is quite legitimate, however, for the TabActivity to know about the tab contents (it created them after all) and to be able to mediate between them. If you simply have Activity 'X' broadcast that a particular action has been performed and allow the TabActivity to receive and act on the Intent type/data then the various siblings don't need to know specifically how each other works.

That would be my approach anyway. :-)

Upvotes: 1

Ted Hopp
Ted Hopp

Reputation: 234795

You could stash the data in an object at the Application level. Then when activity B starts it could check for the data.

Upvotes: 0

Related Questions