1、TabLayout 與 Fragment 結合使用的常見方式
通常會使用 FragmentPagerAdapter 或 FragmentStatePagerAdapter 與 ViewPager 配合,再將 TabLayout 與 ViewPager 關聯,實現通過 TabLayout 切換 Fragment。
以下是布局文件示例 activity_main.xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity"><com.google.android.material.tabs.TabLayout
android:id="@+id/tabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/><andr