I have an activity that has a TabHost containing a set of TabSpecs each with a listview containing the items to be displayed by the tab. When each TabSpec is created, I set an icon to be displayed in the tab header.
The TabSpecs are created in this way within a setupTabs() method which loops to create the appropriate number of tabs:
TabSpec ts = mTabs.newTabSpec("tab"); ts.setIndicator("TabTitle", iconResource); ts.setContent(new TabHost.TabContentFactory( { public View createTabContent(String tag) { ... } }); mTabs.addTab(ts);
There are a couple of instances where I want to be able to change the icon which is displayed in each tab during the execution of my program. Currently, I am deleting all the tabs, and calling the above code again to re-create them.
mTabs.getTabWidget().removeAllViews(); mTabs.clearAllTabs(true); setupTabs();
Is there a way to replace the icon that is being displayed without deleting and re-creating all of the tabs?
The short answer is, you’re not missing anything. The Android SDK doesn’t provide a direct method to change the indicator of a
TabHostafter it’s been created. TheTabSpecis only used to build the tab, so changing theTabSpecafter the fact will have no effect.I think there’s a workaround, though. Call
mTabs.getTabWidget()to get aTabWidgetobject. This is just a subclass ofViewGroup, so you can callgetChildCount()andgetChildAt()to access individual tabs within theTabWidget. Each of these tabs is also a View, and in the case of a tab with a graphical indicator and a text label, it’s almost certainly some otherViewGroup(maybe aLinearLayout, but it doesn’t matter) that contains anImageViewand aTextView. So with a little fiddling with the debugger orLog.i, you should be able to figure out a recipe to get theImageViewand change it directly.The downside is that if you’re not careful, the exact layout of the controls within a tab could change and your app could break. Your initial solution is perhaps more robust, but then again it might lead to other unwanted side effects like flicker or focus problems.