Tag Archives: Mono

How to handle TabHost TabChanged event in Mono Android?

Being new to Android development I struggled with this one for some time and hopefully this post will save some poor soul the agony I went through.

After I added a TabHost widget to my Layout I assumed I could attach an event handler to either the TabSpec component or the TabHost itself and listen to these events in the activity. But this does not work. Googling and trolling stackoverflow threw up old references which no longer were valid for 4.0.1 version of the SDK I am targeting.

However the technique is very simple. 

The TabHost has a method named “SetOnTabChangedListener” which takes in an instance of class implementing the IOnTabChangeListener interface. 

So all you got to do is implement IOnTabChangeListener in your Activity and set the listener on the TabHost like so

TabHost.SetOnTabChangedListener(this)

Your activity class needs to implement only the OnTabChanged method and you are golden. This method is called when any tab is clicked and you may do whatever pleases you in the method. The tabId is passed in as a parameter. This is the same string you used when setting yo individual tabs.

spec = TabHost.NewTabSpec(“home”);

There you have it. Enjoy.

Advertisements