以下是一个简单的TabLayout和ViewPager2结合使用的示例代码:

<com.google.android.material.tabs.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="fixed"
    app:tabGravity="fill"
    app:tabTextColor="@color/tab_text_color"
    app:tabSelectedTextColor="@color/tab_selected_text_color"
    app:tabIndicatorColor="@color/tab_indicator_color"
    app:tabIndicatorHeight="2dp"
    app:tabBackground="@color/tab_background_color" />

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/view_pager2"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
val viewPager2 = findViewById<ViewPager2>(R.id.view_pager2)

// 设置ViewPager2的Adapter
val adapter = MyViewPagerAdapter(this)
viewPager2.adapter = adapter

// 将TabLayout和ViewPager2连接起来
TabLayoutMediator(tabLayout, viewPager2) { tab, position ->
    tab.text = "Tab $position"
}.attach()

在这个示例代码中,我们首先定义了一个TabLayout和一个ViewPager2,然后通过TabLayoutMediator将它们连接起来。在TabLayoutMediator中,我们为每个Tab设置了文本,并将其与ViewPager2中的对应页面关联起来。最后,我们调用了attach()方法,将TabLayout和ViewPager2绑定在一起。需要注意的是,我们需要提供一个自定义的ViewPager2.Adapter来为ViewPager2提供页面内容

TabLayout 结合ViewPage2的示例代码

原文地址: http://www.cveoy.top/t/topic/hsrS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录