更改TabHost标签的背景

本文介绍了一种通过监听TabHost的onTabChanged方法来更改其标签背景颜色的方法。使用自定义背景图片为选中和未选中的状态提供不同的视觉反馈。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

显示效果如下图: 更改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;

public class TabStudyActivity extends Activity {
@Override
public void 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
public void onTabChanged(String tabId) {
updateTabBackground(tabHost);
}
});
}

/**
* 更新Tab标签的背景图
*
@param tabHost
*/
private void 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));
}
}
}
}



转载于:https://www.cnblogs.com/zhaolong_chn/archive/2011/12/18/2291872.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值