I blogged about this recently, but the gist is you need to use StateListDrawable
class. It allows you to create multiple different drawables and associate them with specific states (such as when your tab is selected).
Assuming you have two icons in your resources, icon
and iconselect
, you would set up the StateListDrawable
like this:
Drawable selectedIcon = getResources().getDrawable(R.drawable.iconselect);
Drawable defaultIcon = getResources().getDrawable(R.drawable.icon);
StateListDrawable selector = new StateListDrawable();
selector.addState(new int[0], defaultIcon);
selector.addState(new int[] { R.attribute.state_selected }, selectedIcon);
Notice that for the default (unselected) icon, you pass in an empty array to addState
. For the selected icon, you pass in R.attribute.state_selected
as the state to correlate with the specified icon. Now you can use this combo drawable when setting up your tab:
getTabHost().newTabSpec("tab").setIndicator("Tab 1", selector);