利用我们前几节文章中讲到的关于Java的反射机制(http://emmet1988.iteye.com/admin/blogs/1064621)来实现对系统控件TabHost的“定制”功能。
1.当我们继承自一个TabActivity之后,就可以通过getTabHost()方法得到一个TabHost对象,接着再通过该对象得到TabWidget对象。
final TabHost tabs = getTabHost();
final TabWidget tabWidget = tabs.getTabWidget();
2.接下来改写tabWidget中的各个标签对象的属性值,进而实现“定制”的功能,这里用到的就是Java的反射机制。
for (int i = 0; i < tabWidget.getChildCount(); i++) {
/**
* 设置高度、宽度,不过宽度由于设置为fill_parent,在此对它没效果
*/
tabWidget.getChildAt(i).getLayoutParams().height = height;
tabWidget.getChildAt(i).getLayoutParams().width = width;
/**
* 设置tab中标题文字的颜色,不然默认为黑色
*/
final TextView tv = (TextView) tabWidget.getChildAt(i)
.findViewById(android.R.id.title);
tv.setTextColor(this.getResources().getColorStateList(
android.R.color.white));
/**
* 此方法是为了去掉系统默认的色白的底角
*
* 在 TabWidget中mBottomLeftStrip、mBottomRightStrip
* 都是私有变量,但是我们可以通过反射来获取
*
* 由于还不知道Android 2.2的接口,在这里先加个判断,避免报错
*/
Log.d("debug", "version is "+Build.VERSION.RELEASE);
// 版本信息有的较长,比如2.2.3,2.1.3.1,我们只需要取前面的三位即可。
final String VERSION = Build.VERSION.RELEASE.substring(0, 3);
Log.d("debug", "version is "+VERSION);
if (Float.valueOf(VERSION) <= 2.1) {
try {
Class<TabWidget> tabWidgetClass = (Class<TabWidget>) tabWidget.getClass();
mBottomLeftStrip = tabWidgetClass.getDeclaredField("mBottomLeftStrip");
mBottomRightStrip = tabWidgetClass.getDeclaredField("mBottomRightStrip");
// 判断是否有访问权限的控制
if (!mBottomLeftStrip.isAccessible()) {
// 取消访问权限控制
mBottomLeftStrip.setAccessible(true);
}
if (!mBottomRightStrip.isAccessible()) {
mBottomRightStrip.setAccessible(true);
}
// 设置属性值
mBottomLeftStrip.set(tabWidget,
getResources().getDrawable(R.drawable.alpha_00));
mBottomRightStrip.set(tabWidget, getResources()
.getDrawable(R.drawable.alpha_00));
} catch (Exception e) {
e.printStackTrace();
}
} else {
/**
* 不做任何处理
*/
}
View vvv = tabWidget.getChildAt(i);
if (tabs.getCurrentTab() == i) {
vvv.setBackgroundDrawable(getResources().getDrawable(
R.drawable.tab_enabled));
} else {
vvv.setBackgroundDrawable(getResources().getDrawable(
R.drawable.tab_selected));
}
}
本文介绍如何通过Java的反射机制实现对TabHost的定制功能,包括修改TabWidget中标签对象的属性,如高度、宽度、颜色及底角样式。
1027

被折叠的 条评论
为什么被折叠?



