个人淘宝店铺链接 需要的伙伴可以点击这里
1 布局
<com.google.android.material.tabs.TabLayout
android:id="@+id/tablayout"
android:layout_width="match_parent"
android:layout_height="50dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:tabIndicatorHeight="2dp"
app:tabIndicatorColor="@android:color/holo_red_dark"
app:tabMode="scrollable"
//Android平板需要加上这个选项,不然只会居中展示
app:tabGravity="fill"/>
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/vp_news"
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@id/tablayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:orientation="horizontal"/>
2 TabLayout和ViewPager2的联动
adapter = ViewPageAdapter(this,fragments)
//ViewPager2设置适配器
vp_news.adapter = adapter
//ViewPager2设置滑动监听
vp_news.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels)
// Log.e("TAG","滑动位置 $position")
}
override fun onPageScrollStateChanged(state: Int) {
super.onPageScrollStateChanged(state)
}
override fun onPageSelected(index: Int) {
super.onPageSelected(index)
Log.e("TAG","onPageSelected $index")
//拿到全部的Tab
var tabCount = tablayout.tabCount
for(i in 0 until tabCount){
var tab = tablayout.getTabAt(i)
tab?.apply {
if(position == index){
var textView = customView as TextView
textView.textSize = 30f
}else{
var textView = customView as TextView
textView.textSize = 20f
}
}
}
}
})
//TabLayout和ViewPager2的联动
mediator = TabLayoutMediator(tablayout,vp_news) { tab, position ->
tab.apply {
//做View的初始化
var tabView = TextView(this@NewsActivity)
tabView.text = tabs[position]
customView = tabView
}
}
//调用attach才可以联动
mediator.attach()
ViewPager2的适配器代码,ViewPager2如果内部填充的是Fragment,那么就使用FragmentPageAdapter,如果是View,那么就使用RecyclerView.Adapter
class ViewPageAdapter(activity: FragmentActivity,fragements:List<Fragment>) : FragmentStateAdapter(activity) {
private var fragements:List<Fragment> = fragements
override fun getItemCount(): Int {
return fragements.size
}
override fun createFragment(position: Int): Fragment {
return fragements.get(position)
}
}