Kotlin使用TabLayout

Kotlin使用Tablayout


1.导入依赖包 implementation “com.google.android.material:material:1.0.0”
2.xml文件里使用 com.google.android.material.tabs.TabLayout
3.使用app:属性时会报红,注意添加xmlns:app=“http://schemas.android.com/apk/res-auto”
这里的app就是和我们自定义view时用的declare-styleable类似,没研究…
然后就可以使用app:中的属性设置了,比如指示器,文字颜色等
4.添加Tabitem
for(i in 1…6) {

      var tabitem = tablayout.newTab()
        val view: View =
            LayoutInflater.from(this).inflate(R.layout.tab_item_layout, null)
        var tv = view.findViewById<View>(R.id.tv) as TextView
        tv.setText("tab"+i.toString())
        tabitem.setCustomView(view)
        tablayout.addTab(tabitem)
    }

这里使用自定义的item.xml,毕竟需求总是不定的。
如果设置Tabitem的字体颜色无效,
app:tabSelectedTextColor="@android:color/black"
app:tabTextColor="@android:color/darker_gray"
可以在代码里设置:
tablayout.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
override fun onTabReselected(p0: TabLayout.Tab) {
}
override fun onTabUnselected(p0: TabLayout.Tab) {
p0.customView?.findViewById(R.id.tv)?.setTextColor(Color.GRAY)
}
override fun onTabSelected(p0: TabLayout.Tab) {
p0.customView?.findViewById(R.id.tv)?.setTextColor(Color.BLACK)
}
})
5.如果与viewpager配合使用,使用到setupWithViewPager后,TabLayout会清除所有的的tabitem的文字,所以,适配器要重写getPageTitle函数(调用父类的会导致上述问题),返回对应的tabitem标题。
比如

在这里插入代码片
 override fun getPageTitle(position: Int): CharSequence? {
        return "tab"+position.toString()
    }

这里适用于默认的tabitem,如果使用自定义的tabitem.xml那就不行了,有文字,有图片,咋整,所以这里使用笨办法(能解决问题的都是好方法,哈哈)

在这里插入代码片
tablayout.addOnTabSelectedListener(object :TabLayout.OnTabSelectedListener{
            override fun onTabReselected(p0: TabLayout.Tab) {
            }
            override fun onTabUnselected(p0: TabLayout.Tab) {
                p0.customView?.findViewById<TextView>(R.id.tv)?.setTextColor(Color.GRAY)
                p0.customView?.findViewById<ImageView>(R.id.im)?.setImageResource(R.mipmap.ic_launcher)
            }
            override fun onTabSelected(p0: TabLayout.Tab) {
                p0.customView?.findViewById<TextView>(R.id.tv)?.setTextColor(Color.BLACK)
                p0.customView?.findViewById<ImageView>(R.id.im)?.setImageResource(R.mipmap.ic_launcher)
            }
        })

选择itemtab改变时每次都重新赋值

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值