更改TabHost标签的背景

显示效果如下图: 更改TabHost标签的背景颜色。 

修改思路: 监听TabHost的onTabChanged方法。

更改TabHost标签的背景

 

实现代码:

复制代码
package com.tony.tabstudy;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;

publicclass TabStudyActivity extends Activity {
@Override
publicvoid onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

final TabHost tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();

TabHost.TabSpec spec
= tabHost.newTabSpec("tab1");
spec.setContent(R.id.tab1);
spec.setIndicator(
"主页");
tabHost.addTab(spec);

TabHost.TabSpec spec2
= tabHost.newTabSpec("tab2");
spec2.setContent(R.id.tab2);
spec2.setIndicator(
"主页2", getResources().getDrawable(android.R.drawable.btn_dialog));
tabHost.addTab(spec2);

tabHost.setCurrentTab(
1);

//初始化设置一次标签背景
updateTabBackground(tabHost);


//选择时背景更改。
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
publicvoid onTabChanged(String tabId) {
updateTabBackground(tabHost);
}
});
}

/**
* 更新Tab标签的背景图
*
@param tabHost
*/
privatevoid updateTabBackground(final TabHost tabHost) {
for (int i =0; i < tabHost.getTabWidget().getChildCount(); i++) {
View vvv
= tabHost.getTabWidget().getChildAt(i);
if (tabHost.getCurrentTab() == i) {
//选中后的背景
vvv.setBackgroundDrawable(getResources().getDrawable(android.R.drawable.spinner_background));
}
else {
//非选择的背景
vvv.setBackgroundDrawable(getResources().getDrawable(R.drawable.a));
}
}
}
}
复制代码

你可能感兴趣的:(tabhost)