I am using a TabHost which has 3 tabs. Each tab has a image + text.
spec = tabHost.newTabSpec("MyTasks")
.setIndicator(Html.fromHtml("<b><H2>My Tasks</H2></b>"), getResources().getDrawable(R.drawable.task ))
.setContent(intent);
tabHost.addTab(spec);
I want to change image when I select a tab. I used following code to change it ...
TabWidget tw = getTabWidget();
View leftTabView = tw.getChildAt(0);
leftTabView.setBackgroundDrawable(getResources().getDrawable(R.drawable.tab1_drawable));
tab1_drawable is a xml (selector and items for each state). THIS IS SETTING AND CHANGING BACKGROUND NOT THE IMAGE I SET. How can I change it?
Instead of changing the drawable through code, why not use a state-list drawable? Then you'd just specify a different drawable for the tab when it is selected.
Example, ic_tab_tasks.xml:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@drawable/ic_tab_tasks_selected"
android:state_selected="true" />
<item android:drawable="@drawable/ic_tab_tasks_normal" />
</selector>
Then, when you're setting the tab indicator's drawable initially, just use the state-list drawable.
try this :
private int index_tab = 0;
private TabWidget tabWidget;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.index_layout);
TabHost t = (TabHost)findViewById(R.id.testhost);
t.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
tabChanged(tabId);
}
});
}
public void tabChanged(String tabId) {
if (index_tab != (Integer.valueOf(tabId) - 1)) {
tabWidget.getChildAt(Integer.valueOf(tabId) - 1)
.setBackgroundDrawable(
getResources().getDrawable(R.drawable.tab1_drawable));
tabWidget.getChildAt(index_tab).setBackgroundDrawable(null);
index_tab = Integer.valueOf(tabId) - 1;
}
}