`

tabhost 动态改变tab的背景图

 
阅读更多
在我的项目中  有5个tab  需要在选中某个TAB的时候 背景图片更换掉
我的Activity继承了
MyClass extends TabActivity implements TabHost.TabContentFactory
Tab主界面对应的layout文件就不用说了
网上有很多关于tabhost配置文件需要注意的 这里的话 我再啰嗦一下


<FrameLayout android:id="@android:id/tabcontent" 一定要这样设置
<TabWidget android:id="@android:id/tabs"一定要这样设置


由于系统自带的样式太丑了 我就自定义了一个tab样式
每个TAB样式都有TAB显示文字和背景图片  请下载本文附件参阅tab_spec.xml

现在说到正题了 如果在点击的过程中  选中项背景变色呢
1,首先应该默认给TAB一个背景色
2,在点击过程中  根据TAB发生变化  再重新赋一次背景就OK了
见如下代码


//获取要显示的TAB页图片名称
private int[] drawableArray = Constant.drawableArray ;

//当该TAB选中时,更换背景图片
private int[] drawableSelectedArray = Constant.drawableSelectedArray ;

// 添加一个Tab页
addTab(tabHost, str+num, str, drawableArray[num-1], intent);
//设置初始化加载页面默认被选中项
tabHost.setCurrentTab(0) ;
tabWidget.getChildAt(0).findViewById(R.id.img_ico).setBackgroundResource(drawableSelectedArray[0]) ;


private void addTab(TabHost tabHost, String Tag, String name, int drawableId, Intent intent) {
// 填充
View tabView = LayoutInflater.from(this).inflate(R.layout.tab_spec,
null);
//填充图片(这里是设置默认的背景图片)
ImageView image = (ImageView)tabView.findViewById(R.id.img_ico);
image.setBackgroundResource(drawableId) ;

//填充文本
TextView textView = (TextView) tabView.findViewById(R.id.txt_name);
textView.setText(name);
tabHost.addTab(tabHost.newTabSpec(Tag).setIndicator(tabView)
.setContent(intent));
}

/** 监听切换tab */
private TabHost.OnTabChangeListener tabChange = new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
View view = CrossedWorkMainActivity.this.getTabHost().getCurrentView();

int index = Integer.valueOf(tabId.substring(tabId.length()-1, tabId.length()))-1 ;//获取当前索引
tabIndex = index ;

//获得当前所有的TabWidget
TabWidget widget = CrossedWorkMainActivity.this.getTabHost().getTabWidget() ;
int num = widget.getChildCount() ;
for(int i=0;i<num;i++){
ImageView imageView = (ImageView)widget.getChildAt(i).findViewById(R.id.img_ico) ;
if(tabIndex==i){
//如果某个tab被选中,则更换背景图片
imageView.setBackgroundResource(drawableSelectedArray[i]) ;
}else{
//未选中的,则使用默认背景图
imageView.setBackgroundResource(drawableArray[i]) ;
}
}
}
};
分享到:
评论
2 楼 lanyan_lan 2012-09-22  
wilsonchen 写道
请问您的tab_spec.xml是怎么应用的呢?


添加TAB的时候啊 
private void addTab(TabHost tabHost, String Tag, String name, int drawableId, Intent intent) {
// 填充
View tabView = LayoutInflater.from(this).inflate(R.layout.tab_spec,
null);
1 楼 wilsonchen 2012-09-01  
请问您的tab_spec.xml是怎么应用的呢?

相关推荐

Global site tag (gtag.js) - Google Analytics