TabLayout设置字体为normal

问题由来

项目快上线了,ui给我提出个问题:你这切换栏的字体不对啊!要用normal 字体,你这都是加粗的。我:… 默默的去改吧;
给TabLayout设置 textStyle =“normal” 和 typeface = “normal” 两个属性根本没有起作用,这就十分尴尬了,不知道改怎么解决了。本着有问题,找度娘的习惯,网上找了半天,也没有找到怎么来解决这个问题,心中顿时万马奔腾,哎…
无意发现textview可以通过setTypeface设置字体的类型,我想TabLayout既然能显示文字,里面肯定包含Textview,只要找到Textview问题就解决。

源码分析

进入TabLayout的源码会发现TabLayout是继承自HorizontalScrollView,然后看TabLayout的构造方法:

public TabLayout(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        ThemeUtils.checkAppCompatTheme(context);
        // Disable the Scroll Bar
        setHorizontalScrollBarEnabled(false);
        // Add the TabStrip
        mTabStrip = new SlidingTabStrip(context);
        super.addView(mTabStrip, 0, new HorizontalScrollView.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT));
         // 省略其他无关代码
}

可以看到TabLayout是添加的SlidingTabStrip,而SlidingTabStrip又是继承自LinearLayout的ViewGroup。

TabLayout一般都是和ViewPager在一起使用

找到setupWithViewPager中的方法

final PagerAdapter adapter = viewPager.getAdapter();
    if (adapter != null) {
    // Now we'll populate ourselves from the pager adapter, adding an observer if
    // autoRefresh is enabled
    setPagerAdapter(adapter, autoRefresh);}

这里写图片描述
我们能很清楚的知道ViewPager和TabLayout是如何绑定在一起的,为什么ViewPager和TabLayout绑定在一起后ViewPager的滑动监听事件不管用,而可以通过TabLayout来监听滑动。
最终我们会发现是把TabView添加到TabLayout中
这里写图片描述

终于找到TextView,我们也就可以改变TabLayout的字体了。

代码实现

public void setTextNormal(TabLayout tab){
        LinearLayout layout = (LinearLayout) tab.getChildAt(0);
        for (int i = 0,len = layout.getChildCount() ; i <len; i++){
            LinearLayout tabView = (LinearLayout) layout.getChildAt(i);
            int t = tabView.getChildCount();
            if (null != tabView && tabView.getChildCount() >0){
                View view = tabView.getChildAt(1);
                if (null != view && view instanceof TextView) {
                    ((TextView) view).setTypeface
            (Typeface.defaultFromStyle(Typeface.NORMAL));
                }
            }
        }
    }

实现是不是超级简单,当遇到问题的时候要学会从别的地方去找解决问题的方法。
多看源码对自己肯定有很大的提升

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值