Android Kotlin TabLayout 拓展:原生TabLayout其实也很香

3,822 阅读2分钟

google 原生 Tablayout( com.google.android.material.tabs.TabLayout) 零入侵拓展,帮你更便捷的使用原生TabLayout实现一些UI效果

预览


关于tablayout-ext

tablayout-ext只是作为google material 库内tablayout控件的一个拓展,旨在于用毫无入侵且比较简单方便的方式使用tablayout的一些属性。作为一个原生组件迷,对github上各种大佬开源的tablayout也是十分倾佩的,但无论是在用法或是情节上,我总想用原生的控件去实现UI上的要求。再到使用 ViewPager2  |  Android Developers 之后,发现原生控件之间的互相支持确实值得称赞。所以原生控件其实也很香,为什么不用起来呢?

tablayout-ext目前只实现了一些非常常规的用法,采用kotlin拓展函数来进行链式调用。受限于原生tablayout的源码结构,诸如选中文字字体变大等需求,到目前为止我仍在思考如何在不入侵tablayout代码的情况下实现。读到这里,如果你有一个很好的实现思路,希望能在评论中不吝赐教。

此库会持续更新,但更新时间不定,如果你在项目中使用到了此库并遇到了问题,可以在Github中找到我,并给Tablayout-ext提出 issue,我会在第一时间尝试处理这个问题。

如何引入

Step 1. 添加 JitPack repository

allprojects {
	repositories {
		...
		maven { url "https://jitpack.io" }
	}
}

Step 2. 添加 Gradle依赖

dependencies {
    ...
    implementation 'com.google.android.material:material:1.2.1'//google material 包
    implementation 'com.github.loperSeven:tablayout-ext:0.0.1'//此处不保证是否是最新版本,最新版本请前往github查看,仅支持androidX
}


如何使用

注意:此库只是针对Tablayout做一些便捷性拓展,具体Tablayout属性及用法请查阅:developers 文档

Indicator

  /**
    * 线性指示器
    * buildIndicator<> 指定指示器类
    * setHeight() 设置指示器高度,默认为tablayout指定tabIndicatorHeight高度
    * setWidth() 设置指示器宽度,若tablayout设置了tabIndicatorFullWidth=true,则默认为tab项宽度,否则为tab实际文字宽度
    * setGravity() 等同于 Tablayout.setSelectedTabIndicatorGravity()
    * setColor() 等同于 Tablayout.setSelectedTabIndicatorColor()
    */
 tabLayout.buildIndicator<LinearIndicator>()
            .setHeight(22.toPx())
            .setWidth(BaseIndicator.MATCH)
            .setGravity(TabLayout.INDICATOR_GRAVITY_TOP)
            .setColor(ContextCompat.getColor(context!!,R.color.colorAccent))
            .bind()
 /**
    * 三角形指示器
    * buildIndicator<> 指定指示器类
    * setPath 设置三角形样式 [POSITIVE]正 [NEGATIVE] 反
    */
 tabLayout.buildIndicator<TriangleIndicator>()
            .setPath(TriangleIndicator.Path.NEGATIVE)//因path为该指示器专有属性,故需先于其他属性调用。
            .setWidth(10.toPx())
            .setHeight(10.toPx())
            .setColor(ContextCompat.getColor(context!!,R.color.colorAccent))
            .setGravity(TabLayout.INDICATOR_GRAVITY_TOP)
            .bind()
	    
 /**
    * 自定义deawable指示器
    * buildIndicator<> 指定指示器类
    * setDrawable 设置指示器drawable 可传入 Drawable 或 @DrawableRes resId:Int
    * 其他属性同上,皆为基础属性
    */
  tabLayout.buildIndicator<CustomIndicator>()
            .setDrawable(ContextCompat.getDrawable(context!!,R.mipmap.ic_indicator_fire)!!)
            .bind()
	    

如需拓展更多类型指示器,只需继承自BaseIndicator,添加专属属性,在bind()方法中实现逻辑即可。

Text

 /**
    * tab文字设置
    * buildText<> 指定文字设置类
    * setNormalTextBold() 未选中状态下文字是否加粗  默认false
    * setSelectTextBold() 选中状态下文字是否加粗 默认true
    */
  tabLayout.buildText<BaseText>()
            .setNormalTextBold(true)
            .setSelectTextBold(true)
            .bind()

混淆

-dontwarn com.loper7.tablayout-ext.**
-keep class com.loper7.tablayout-ext.**{*;}

Github

Tablayout-ext