第一步,新建项目。
第二步,修改xml文件
第三步。添加关键代码
public class tab extends TabActivity {
TabHost mTabHost;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setupTabs();
}
private void setupTabs(){
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_1").setIndicator(
"Tab 1").setContent(R.id.tv1));
mTabHost.addTab(mTabHost.newTabSpec("tab_2").setIndicator(
"Tab 2").setContent(R.id.tv2));
mTabHost.addTab(mTabHost.newTabSpec("tab_3").setIndicator(
"Tab 3").setContent(R.id.tv3));
mTabHost.addTab(mTabHost.newTabSpec("tab_4").setIndicator(
"Tab 4").setContent(R.id.tv4));
mTabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabTag) { // tab选中状态变更时
int tabId = mTabHost.getCurrentTab();
changeTab(tabId);
}
});
}
private void changeTab(int tabId){
LinearLayout ll=(LinearLayout)mTabHost.getChildAt(0);
TabWidget tw=(TabWidget)ll.getChildAt(0);
// 以上两行代码,找到TabWidget
int tabCount=tw.getChildCount();
for (int i=0; i<tabCount; i++){
RelativeLayout rl=(RelativeLayout)tw.getChildAt(i);
TextView tv=(TextView)rl.getChildAt(1);
// 以上两行代码,找到要修改属性的TextView
String tabLabel="Bye!";
int color=Color.WHITE;
if (i==tabId){ // 如果是选定tab,则修改之
tabLabel="Hello!";
color=Color.RED;
}
tv.setText(tabLabel);
tv.setTextColor(color);
//以上两行代码,修改TextView的属性
}
}
}