美文网首页
Android TabLayout选中字体加粗

Android TabLayout选中字体加粗

作者: zyguo | 来源:发表于2019-07-31 17:54 被阅读0次

    最近项目的美术需求里有一条,Tab选中态的时候字体需要加粗。TabLayout可以设置选中/非选中态字体的颜色,但是却没有找到设置选中态字体加粗的方法。

    一种解决方案是继承TabLayout,但是考虑到UI需求随时可能变化,并且厌倦了各种fucking MyXXXView,决定采用另一种方法:反射。

    核心代码如下,用的是kotlin:

        /**
         * 通过反射来设置选中字体加粗
         */
        private fun TabLayout.Tab.selectText(selected: Boolean) {
            this.apply {
                try{
                    val fieldView = javaClass.getDeclaredField("view")
                    fieldView.isAccessible = true
                    val view = fieldView.get(this)
                    val fieldText = view.javaClass.getDeclaredField("textView")
                    fieldText.isAccessible = true
                    val tabSelect = fieldText.get(view) as TextView
                    if (selected) {
                        tabSelect.typeface = Typeface.defaultFromStyle(Typeface.BOLD)
                    } else {
                        tabSelect.typeface = Typeface.defaultFromStyle(Typeface.NORMAL)
                    }
                    tabSelect.text = this.text
                }
                catch(e: Exception) {}
            }
        }
    

    需要注意的是,不同版本的TabLayout内部的view tree可能不同,具体使用的时候看下源码微调一下field name就可以了

    另外,由于用到了反射,记得更新proguard~~

    相关文章

      网友评论

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

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