2

I have seen multiple examples on how to set the Selected and Unselected icon of a TabHost like this SO question here: How to change the Tabs Images in the TabHost

However, I do not want to use the XML file. I would like to know how to set these icons programmatically.

Any ideas??

Community
  • 1
  • 1
AngeloS
  • 5,536
  • 7
  • 40
  • 58

4 Answers4

1

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);
Kirk Woll
  • 76,112
  • 22
  • 180
  • 195
1

Take a look at this example of how to fully customize tabs in a TabHost. I used this for my app, and had complete control over everything. The link shows how to do it with XML, but you should be able to convert it over to set the backgrounds, etc. in code:

http://joshclemm.com/blog/?p=136

hooked82
  • 6,336
  • 4
  • 41
  • 46
  • Thanks for your reply. Unfortunately, it does not clearly show how to programmatically set the selected and unselected icon states. The linked question in my question shows this same method of using XML. – AngeloS Aug 23 '11 at 15:54
0

Programmatically change image of TabHost selected and unselected icons

ImageView image= (ImageView) mTabHost.getTabWidget().getChildTabViewAt(tabPosition).findViewById(android.R.id.icon);

image.setImageResource(R.drawable.ic_more_vert_white_24dp);
Vasily Kabunov
  • 6,511
  • 13
  • 49
  • 53
Irfan Shah
  • 11
  • 3
0

Unfortunately, this is not possible (or there is no easier ways to achieve this except of specified question).

Andrei Buneyeu
  • 6,662
  • 6
  • 35
  • 38