Implementing Tab Layouts with ViewPager in Android
Integrating TabLayout with ViewPager in Android
A common UI pattern in Android applications involves using a tabbed interface at the top of the screen. This is typically implemented using a TabLayout from the Material Components library in conjunction with a ViewPager or ViewPager2. The TabLayout provides the visual tabs, while the ViewPager handles the horizontal swiping between content pages, usually Fragment instances.
Core Implementation Steps
-
Add Dependencies and Layout Components: Ensure the Material Components library is included in your
build.gradlefile. In your Activity's layout XML, add both aTabLayoutand aViewPager.<com.google.android.material.tabs.TabLayout android:id="@+id/tabs" android:layout_width="match_parent" android:layout_height="wrap_content" /> <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@id/tabs" /> -
Create Fragment Content: Define separate
Fragmentclasses for the content to be dislpayed under each tab.class FirstTabFragment : Fragment() { override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { return inflater.inflate(R.layout.fragment_first, container, false) } } -
Implement the Pager Adapter: Create a
FragmentPagerAdapterorFragmentStatePagerAdapter(for a larger number of tabs) to manage the fragments. This adapter is responsible for instantiating the correct fragment for each position and providing the tab title.class ScreenSlidePagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) { override fun getCount(): Int = 2 override fun getItem(position: Int): Fragment { return when (position) { 0 -> FirstTabFragment() 1 -> SecondTabFragment() else -> throw IllegalArgumentException("Invalid position") } } override fun getPageTitle(position: Int): CharSequence? { return when (position) { 0 -> "First Tab" 1 -> "Second Tab" else -> null } } } -
Connect Components in Activity: In your Activity's
onCreatemethod, initialize theViewPager, set its adapter, and link it to theTabLayout.class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val pagerAdapter = ScreenSlidePagerAdapter(supportFragmentManager) val viewPager: ViewPager = findViewById(R.id.viewpager) viewPager.adapter = pagerAdapter val tabLayout: TabLayout = findViewById(R.id.tabs) tabLayout.setupWithViewPager(viewPager) } }
The call to TabLayout.setupWithViewPager(viewPager) synchronizes the tab selection with the ViewPager's current item. The tab titles are automatically sourced from the adapter's getPageTitle method.