用户登录
用户注册

分享至

Kotlin使用TabLayout

  • 作者: 活在当下123
  • 来源: 51数据库
  • 2021-08-31

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改变时每次都重新赋值

软件
前端设计
程序设计
Java相关