效果图
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/f0d6b3c726f145fa8c85c9850925f3a4.gif#pic_center)
添加引用
- 在
settings.gradle.kts
中添加maven配置dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
maven { setUrl("https://jitpack.io") }
...
}
}
- 在app的
build.gradle
中增加引用dependencies {
...
implementation("com.github.angcyo.DslTablayout:TabLayout:3.5.5")
implementation("com.github.angcyo.DslTablayout:ViewPager2Delegate:3.5.5")
}
使用
- xml布局文件中
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.angcyo.tablayout.DslTabLayout
android:id="@+id/tabLayout"
android:layout_width="0dp"
android:layout_height="40dp"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tab_draw_badge="true"
app:tab_enable_gradient_scale="true"
app:tab_indicator_drawable="@drawable/shape_item_tab"
app:tab_indicator_enable_flow="true"
app:tab_indicator_style="STYLE_CENTER"
app:tab_item_auto_equ_width="true"
app:tab_max_scale="1.1"
app:tab_min_scale="0.9" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toBottomOf="@id/tabLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
- kotlin代码
bind.viewPager.adapter = CustomAdapter()
titles.forEach { title ->
LayoutItemTablayoutBinding.inflate(layoutInflater).let {
it.root.text = title
bind.tabLayout.addView(it.root)
bind.tabLayout.onTabBadgeConfig = { child, tabBadge, index ->
when (index) {
2 -> {
tabBadge.apply {
badgeOffsetY = maxHeight / 2
badgeOffsetX = 10.dp2px()
badgeGravity = Gravity.RIGHT or Gravity.TOP
badgeText = "99"
}
}
else -> {
tabBadge.apply {
badgeCircleOffsetY = -maxHeight / 2
badgeText = ""
}
}
}
tabBadge.updateOriginDrawable()
null
}
}
}
ViewPager2Delegate.install(bind.viewPager, bind.tabLayout, false)
demo下载地址
demo下载地址
参考文献
1. https://github.com/angcyo/DslTabLayout