添加依赖
implementation "com.google.android.material:material:1.1.0"
implementation 'androidx.viewpager2:viewpager2:1.0.0'
1.页面布局
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.google.android.material.tabs.TabLayout
android:id="@+id/tableLayout"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_gravity="center_horizontal"
app:tabIndicatorFullWidth="false"
app:tabTextColor="#2196F3" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/mainViewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</FrameLayout>
2.随便创建三个Fragment,这里命名为OneFragment、TwoFragment、ThreeFragment 3.MainActivity实现代码
class MainActivity : AppCompatActivity() {
private lateinit var mainVideoPlayer: ViewPager2
private lateinit var tableLayout: TabLayout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mainVideoPlayer = findViewById(R.id.mainViewPager)
tableLayout = findViewById(R.id.tableLayout)
mainVideoPlayer.apply {
adapter = object : FragmentStateAdapter(this@MainActivity) {
override fun getItemCount() = 3
override fun createFragment(position: Int): Fragment {
return when (position) {
1 -> OneFragment()
2-> TwoFragment()
else->ThreeFragment()
}
}
}
setCurrentItem(1, false)
}
TabLayoutMediator(tableLayout, mainVideoPlayer) { tab: TabLayout.Tab, i: Int ->
tab.text = when (i) {
1 -> "One"
2-> "Two"
else-> "Three"
}
}.attach()
}
}
4.TabLayout控件属性
app:tabIndicatorColor :指示线的颜色
app:tabIndicatorHeight :指示线的高度
app:tabSelectedTextColor : tab选中时的字体颜色
app:tabTextColor:tab未选中时的字体颜色
app:tabMode="scrollable" : 默认是fixed,固定的;scrollable:可滚动的
app:tabBackground:背景色,这个需要在color文件定义好,再引用,不然容易报错
app:tabIndicatorFullWidth:指示器宽度是否充满,fasle代表跟随文字宽度
app:tabRippleColor ="@android:color/transparent":取消掉Tab选项卡点击时候的Ripple水波纹效果
app:tabIndicator : 自定义指示器的圆角或者宽度,使用drawable创建
官方开发文档
https://developer.android.google.cn/reference/com/google/android/material/tabs/TabLayout
|