Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Implementing Tab Layouts with ViewPager in Android

Tech May 7 6

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

  1. Add Dependencies and Layout Components: Ensure the Material Components library is included in your build.gradle file. In your Activity's layout XML, add both a TabLayout and a ViewPager.

    <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" />
    
  2. Create Fragment Content: Define separate Fragment classes 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)
        }
    }
    
  3. Implement the Pager Adapter: Create a FragmentPagerAdapter or FragmentStatePagerAdapter (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
            }
        }
    }
    
  4. Connect Components in Activity: In your Activity's onCreate method, initialize the ViewPager, set its adapter, and link it to the TabLayout.

    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.

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.