美文网首页程序猿之家
Android TabLayout选中字体加粗

Android TabLayout选中字体加粗

作者: 我该怎么 | 来源:发表于2018-07-13 09:15 被阅读154次

    最近项目有一个需求,就是标题的选中项需要加粗,由于项目中使用的都是TabLayout 而TabLayout又没有相应的属性支持,只好自己想办法了!

    在网上找了半天,发现都是讲TabLayout 基本使用的,没有找到自己想要的东西,只好重另外一个角度来解决,TabLayout 可以自定义选中项的UI,所以可以从这方面入手,

    最后的解决办法是为TabLayout 添加一个监听,并在监听中自定义选中项UI,代码和布局文件如下

     tablayoutTablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                @Override
                public void onTabSelected(TabLayout.Tab tab) {
                    View view = tab.getCustomView();
                    if (null == view) {
                        tab.setCustomView(R.layout.custom_tab_layout_text);
                    }
                    TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
                    textView.setTextColor(tablayoutTablayout.getTabTextColors());
                    textView.setTypeface(Typeface.DEFAULT_BOLD);
                }
    
                @Override
                public void onTabUnselected(TabLayout.Tab tab) {
                    View view = tab.getCustomView();
                    if (null == view) {
                        tab.setCustomView(R.layout.custom_tab_layout_text);
                    }
                    TextView textView = tab.getCustomView().findViewById(android.R.id.text1);
                    textView.setTypeface(Typeface.DEFAULT);
                }
    
                @Override
                public void onTabReselected(TabLayout.Tab tab) {
    
                }
            });
    

    用到的布局文件如下

    <?xml version="1.0" encoding="utf-8"?>
    <TextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@android:id/text1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        />
    

    需要注意的是 监听一定要在setupWithViewPager方法之前添加,否则会有bug

    相关文章

      网友评论

        本文标题:Android TabLayout选中字体加粗

        本文链接:https://www.haomeiwen.com/subject/cjadpftx.html