Question

I want to change the background image of tabs when they're selected and unselected. I've followed a few ways to do it from other questions but they didn't seem to work, could you check my code and see what I'm doing wrong? (The question I talked of - How to change the Tabs Images in the TabHost )

Below is the tab in MainActivity

TabSpec specs = th.newTabSpec("Tab1");
    specs.setContent(R.id.tab1);
    specs.setIndicator("Tab 1",
            res.getDrawable(R.drawable.tab1_selector));
    th.addTab(specs);

Below is the xml

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use icon1 -->
<item android:drawable="@drawable/selected"
  android:state_selected="true" />
<!-- When not selected, use icon2-->
<item android:drawable="@drawable/unselected"
  android:state_selected="false" />
</selector>

Thanks, Tom.

Was it helpful?

Solution

Updated answer..You should rather use this method TabSpecs.setIndicator(View view) and provide it a View instance (probably a LinearLayout with TextView in it) and set the drawable as a background of the view.

Create a new XML layout resource containing LinearLayout with one nested TextView as a layout for your tab..Then you should create a function which Inflates that XML to a View instance and sets the TextView content (title of the tab)..then you should call the setIndicator() method with this view..It will effectively replace whole content of your tab with that view.

View v = LayoutInflater.from(this).inflate(R.layout.tab_layout, tabHost.getTabWidget(), false);
TextView label = (TextView) v.findViewById(R.id.textView);
label.setText("Title of your tab");

The method you've used only sets the drawable as an icon (according to docs), so that could be the issue..

Alternatively you can set the theme this way. It should work.

 <style name="MyCustomTheme" parent="@android:style/Theme.Holo.Light">
    <item name="android:tabWidgetStyle">@style/CustomTabWidget</item>
</style>

<style name="CustomTabWidget" parent="@android:style/Widget.TabWidget">
    <item name="android:background">@drawable/your_drawable</item>
</style>

Or you can just try to get direct reference to tabs from your code. Somehow like this.

for(int i=0;i<tabHost.getTabWidget().getChildCount();i++) {
    tabHost.getTabWidget().getChildAt(i).setBackground(R.drawable.your_drawable); 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top