字体粗细问题:
TabLayout 标题的字体默认是加粗的。并且如果你在xml文件中设置typeface也是没用的。
<android.support.design.widget.TabLayout
android:id="@+id/main_tab"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabBackground="@drawable/app_click_background_selector"
app:tabGravity="center"
app:tabIndicatorColor="#FA931D"<!-下划线颜色-->
app:tabIndicatorHeight="@dimen/IndicatorHeight"<!-下划线高度-->
app:tabSelectedTextColor="#FA931D"<!-选中字体颜色-->
app:tabTextAppearance="@style/MyCustomTabTextAppearance"
app:tabTextColor="#999999" />
<style name="MyCustomTabTextAppearance" parent="TextAppearance.Design.Tab">
<!--TAB文字样式-->
<item name="android:textSize">14sp</item>
<item name="android:typeface">normal</item>
</style>
所以我们要在代码中把TextView找出来,并重新设置它的字体是否要加粗。
我们通过设置TabLayout的选中监听setOnTabSelectedListener获取当前选中的tab的position
注意:我们一旦设置了选中监听,点击tab时ViewPager就不会跟着tab滚动,此时需要手动滚动ViewPager
mMainTabTitle.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
int position = tab.getPosition();
//选中加粗字体
ViewUtils.setTabTextStyle(mMainTabTitle, true, position);
mMainViewPager.setCurrentItem(tab.getPosition(),false);
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
int position = tab.getPosition();
//不选中细字体
ViewUtils.setTabTextStyle(mMainTabTitle, false, position);
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
通过传进来的position,拿到当前选中的TabView,再从其中找到用它的TextView.就可以设置字体粗细了。
/**
* 设置TabLayout中的字体是否要加粗
* @param tabLayout
* @param isBold
* @param position
*/
public static void setTabTextStyle(TabLayout tabLayout, boolean isBold, int position) {
try {
LinearLayout ly = (LinearLayout) tabLayout.getChildAt(0);
LinearLayout tabView = (LinearLayout) ly.getChildAt(position);
if (null != tabView && tabView.getChildCount() > 0) {
View view = tabView.getChildAt(0);
if (null != view && view instanceof AppCompatTextView) {
if (isBold) {
((AppCompatTextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
} else {
((AppCompatTextView) view).setTypeface(Typeface.defaultFromStyle(Typeface.NORMAL));
}
}
}
}catch (Exception e){
e.printStackTrace();
}
}
以上方法有个问题:第一次加载进来的时候字体还是加粗的。所以第一次需要遍历一下tabView一个个去设置一下字体粗细。
是否可点击:
如果在xml文件中设置TabLayout的clickable的话对tab是不起作用的。所以我们需要对TabLayout中的所有Tab都 设置一遍,才能生效:
/**
* 设置TabLayout是否可以点击
*
* @param clickable
*/
public static void setTabClick(TabLayout tabLayout, boolean clickable) {
LinearLayout tabStrip = (LinearLayout) tabLayout.getChildAt(0);
for (int i = 0; i < tabStrip.getChildCount(); i++) {
View tabView = tabStrip.getChildAt(i);
if (tabView != null) {
tabView.setClickable(clickable);
}
}
if (clickable) {
tabLayout.setAlpha(1f);
} else {
tabLayout.setAlpha(0.5f);
}
}