Customize Android TabHost TabWidget

Sometimes I want to simply make a bit of adjustment to default tab in Android UI. Instead of something dreadful, to something more cheerful like red or such. Here is some way to customize it.

1. Implement OnTabChangeListener to TabActivity class of your choice
1.1 Add some little tidbits here and tehre
[java]
public class MainActivity extends TabActivity implements OnTabChangeListener {

private int preferredTab = 0;
private Resources res;
private TabHost tabHost;

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// set the main content
setContentView(R.layout.main_activity);

// Resource object to get
res = getResources();
// The activity TabHost
tabHost = getTabHost();
// set listener to tabhost IMPORTANT IMPORTANT
tabHost.setOnTabChangedListener(this);

//load tab with spec and such

tabStyling(); //to be added later
}

}

@Override
public void onTabChanged(String tabId) {
//some code here

}

//some code here

}
[/java]

2. Add this tabstyling method into activity class.

[java]

private void tabStyling() {

// change tab background color to red
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#990000"));

/**
* set height and width under TabActivity setting width has no
* effect due to fill_parent layout parameter
*/
//NOTE i cannot get this part work properly.
//tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 30;
//tabHost.getTabWidget().getChildAt(i).getLayoutParams().width = 30;

View tempView= tabHost.getTabWidget().getChildAt(i);
/**
* I kept all drawables in selector so that the we could get correct
* drawablea applied to tabs as the selector pointed to has both the
* tabs and the bottom tab-bar drawables referenced
*/
//tempView.setBackgroundDrawable(res.getDrawable(R.drawable.somedrawable));

}

// o set different color for current selected tab to blue
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#009900"));
}
[/java]

3. Set OnTabChange() Listener

[java]
@Override
public void onTabChanged(String tabId) {

for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i).setBackgroundColor(
Color.parseColor("#990000"));
}
tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab())
.setBackgroundColor(Color.parseColor("#009900"));

}
[/java]

done.

Any question just let me know

7 thoughts on “Customize Android TabHost TabWidget

  1. monster123

    How do i change the width of the tabs such that a maximum of only two tabs are visible at a time?

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>