做小项目到时候需要自建TabLayout并且自定义TabItem,折腾了一下午,实现了功能,遇到两个坑予以记录:
1.添加自定义View到TabLayout中
TabLayout自带到TabItem拓展性太差,图片和文字到位置不能自由定制,导致显示效果不佳,因此最好自己动态添加Tab。本次是添加了一个带有Icon的TextView到TabLayout中,具体实现代码如下:
for (int i = 0; i < 4; i++) {
TextView newTab = new TextView(BaseMyApplication.mContext);
Drawable drawable = null;
String text = null;
switch (i) {
case 0:
drawable = getResources().getDrawable(R.drawable.selector_home);
drawable.setBounds(0, 0, 50, 50);
text = "首页";
break;
case 1:
drawable = getResources().getDrawable(R.drawable.selector_expert);
drawable.setBounds(0, 0, 50, 50);
text = "专家";
break;
case 2:
drawable = getResources().getDrawable(R.drawable.selector_competition);
drawable.setBounds(0, 0, 50, 50);
text = "赛场";
break;
case 3:
drawable = getResources().getDrawable(R.drawable.selector_my);
drawable.setBounds(0, 0, 50, 50);
text = "咨询";
break;
}
newTab.setCompoundDrawables(null, drawable, null, null);
newTab.setText(text);
newTab.setTextSize(16);
newTab.setGravity(Gravity.CENTER_HORIZONTAL);
ColorStateList colorStateList = getResources().getColorStateList(R.color.selector_tab_item);
newTab.setTextColor(colorStateList);
tableLayout.addTab(tableLayout.newTab().setCustomView(newTab));
}
其中主要的代码就是TabLayout的addTab方法,传入的是一个Tab对象,而Tab对象是通过TabLayout的newTab方法创建的,创建以后通过设置CustomView可以设置Tab的实际View。
2.为TextView设置正确到颜色选择器
在为TextView配置颜色选择器的时候又遇到了坑,通过getColor的方法获取到的颜色只有一个值,即使使用color是一个selector还是一个值,所以不能用此方法,应该使用另一个方法,具体实现代码如下:
TextView textview = new TextView(context);
ColorStateList colorStateList = getResources().getColorStateList(R.color.selector_tab_item);
textview.setTextColor(colorStateList);
使用getColorStateList方法可以获得一个对应状态的颜色列表,设置给TextVIew。
同时需要注意的时在TabLayout中,TextView的切换状态为Selected,因此selector中的state必须写为selected,写为其他状态均不能达到选择Tab后切换状态的效果,具体实现代码如下:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:color="@color/tabred" android:state_selected="true" />
<item android:color="@color/tabblack" android:state_selected="false" />
</selector>
440



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



