# 7. Implementation of Tab Layout

The tab layout is often used for navigation systems that allow swiping between different screens (in conjunction with a ViewPager), and this can often be done as the first level of navigation or the second. Unlike the implementation for the bottom navigation bar, most of the code used to set up the tab layout belongs in the logic files rather than the layout XML.&#x20;

## Preliminary Steps

### Step 0: Importing the material design library:

Same as the implementation for the bottom navigation bar, you'll need to add the material design library to `build.gradle` to use the tab layout.&#x20;

{% code title="build.gradle (Module: app)" %}

```bash
implementation 'com.google.android.material:material:1.2.1'
```

{% endcode %}

### Step 1: Creating `Fragments` or views

First, you'll want to create all the fragments that you'll need for the tab layout. You can do this easily by navigating to **\[Right click] > New > Fragment > Fragment (Blank)**. In our example, the fragment will contain a `TextView` with the fragment name inside:&#x20;

{% code title="FragmentA.kt" %}

```kotlin
class FragmentA : Fragment() {
    private lateinit var textView: TextView

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_a, container, false)
        textView = view.findViewById(R.id.textviewA)
        textView.text = "A"
        return view
    }

    companion object {
        @JvmStatic
        fun newInstance() = FragmentA()
    }
}
```

{% endcode %}

If you need a refresher on what Fragments are or what these methods mean, you can visit:&#x20;

{% content-ref url="5.-fragments/5.1-what-are-fragments" %}
[5.1-what-are-fragments](https://android-course.cornellappdev.com/archive/archived-native-android-textbook-pages/5.-fragments/5.1-what-are-fragments)
{% endcontent-ref %}

We'll also go ahead and create another Fragment in the same way as above and call it **FragmentB**.&#x20;

## TabLayout with ViewPager

Screen slides are transitions between one entire screen to another and are common with UIs like setup wizards or slideshows. The [`ViewPager`](https://developer.android.com/reference/androidx/viewpager/widget/ViewPager)allows us to do screen slides easily with fragments and can animate screen slides automatically.  ViewPagers integrate well with TabLayouts in the sense where if you slide the ViewPager, the tabs will change to correspond! There was a brief introduction to ViewPagers without TabLayouts in[ section 6.4](https://android-course.cornellappdev.com/archive/archived-native-android-textbook-pages/5.-fragments/5.4-implementation-with-fragments)!

### Step 1: Adding `TabLayout` and `ViewPager2` to XML

Next in the XML of our activity, we'll need to add the `TabLayout` and `ViewPager2`. The tab layout holds the different tabs and manages the swiping visual cue  when the user switches screens. The view pager is the container that holds the view or fragment.&#x20;

We can just add the two UI components like so, with `TabLayout` above `ViewPager2:`

{% code title="activity\_main.xml" %}

```markup
<com.google.android.material.tabs.TabLayout
    android:id="@+id/tab_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="?android:attr/actionBarSize"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<androidx.viewpager2.widget.ViewPager2
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/tab_layout" />
```

{% endcode %}

### Step 2: Wire up the fragments to `ViewPager2`

Inside of our activity in `onCreate()`, we'll just have to dictate how the position of the view pager affects the content inside:&#x20;

{% code title="MainActivity.kt" %}

```kotlin
override fun onCreate(savedInstanceState: Bundle?) {
    viewPager = findViewById(R.id.view_pager)
    
    // create new fragment adapter for the view pager
    viewPager.adapter = object : FragmentStateAdapter(this) {
        override fun createFragment(position: Int): Fragment {

            // return the correct fragment based on the position 
            // of the view pager
            return when (position) {
                0 -> FragmentA.newInstance()
                1 -> FragmentB.newInstance()
                else -> FragmentA.newInstance() // else is required, this should never happen as long
                // as getItemCount accurately reflects the number of fragments you have!
            }
        }
    
        // get the number of pages in the view pager
        override fun getItemCount(): Int {
            return 2
        }
    }
}
```

{% endcode %}

Setting up the adapter for the view pager just requires us to override two function `createFragment(...)` and `getItemCount()`, and as you can see above, it's not too difficult to set up.

### Step 3: Wiring `ViewPager2` to `TabLayout`

Finally, we just have to add functionality to the tabs in `TabLayout` so that the view pager knows which page to switch to, and all of this can be done through the `TabLayoutMediator`. This will also be the method that handles the naming of the tabs.&#x20;

{% code title="MainActivity.kt" %}

```kotlin
tabLayout = findViewById(R.id.tab_layout)
TabLayoutMediator(tabLayout, viewPager) { tab, position ->
    when (position) {
        0 -> tab.text = "Fragment A"
        1 -> tab.text = "Fragment B"
    }
}.attach()
```

{% endcode %}

At this point, if we run the emulator, we should see an application that looks something like this, and the user can swipe between the different screens, where each screen is a different fragment.&#x20;

![Emulator](https://195521982-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LvOeSx5ZqjJA8sxykMu%2F-MJnABitd1RX5OLR3zhA%2F-MJsAJxq4RKnRFXlppaM%2Fimage.png?alt=media\&token=6c3026ca-d265-493c-ab6f-8dca98333bb5)

{% hint style="warning" %}
A unique property of ViewPagers is that it preloads a certain number of pages to the left and right of your currentPage when the adapter is first created in the flow of your app which makes it hard to dynamically respond to changes!

If you are modifying other fragments in your ViewPager or trying to share data in between using techniques from [5.5-sharing-data-between-fragments](https://android-course.cornellappdev.com/archive/archived-native-android-textbook-pages/5.-fragments/5.5-sharing-data-between-fragments "mention"), you MUST call on [notifyItemChanged](https://developer.android.com/reference/androidx/recyclerview/widget/RecyclerView.Adapter#notifyItemChanged\(int\)) after to refresh the stale data in your fragment from when it was preloaded. NotifyItemChanged takes in the index of the Fragment being refreshed.&#x20;

ex: viewPager2.adapter.notifyItemChanged(0)
{% endhint %}

## TabLayout without ViewPagers

You can also manually handle the transitions between the clicking of tabs yourself which may offer more flexibility!

Population of the tabs to display is done through [`TabLayout.Tab`](https://developer.android.com/reference/com/google/android/material/tabs/TabLayout.Tab) instances. You create tabs via [`newTab()`](https://developer.android.com/reference/com/google/android/material/tabs/TabLayout#newTab\(\)). From there you can change the tab's label or icon via [`TabLayout.Tab.setText(int)`](https://developer.android.com/reference/com/google/android/material/tabs/TabLayout.Tab#setText\(int\)) and [`TabLayout.Tab.setIcon(int)`](https://developer.android.com/reference/com/google/android/material/tabs/TabLayout.Tab#setIcon\(int\)) respectively. To display the tab, you need to add it to the layout via one of the [`addTab(Tab)`](https://developer.android.com/reference/com/google/android/material/tabs/TabLayout#addTab\(com.google.android.material.tabs.TabLayout.Tab\)) methods.&#x20;

For example:

```kotlin
val tabLayout = findViewById<TabLayout>(R.id.tab_layout)
tabLayout.addTab(tabLayout.newTab().setText("Home"))
tabLayout.addTab(tabLayout.newTab().setText("Profile"))
```

You can then listen in to changes in the TabLayout programatically:

```kotlin
tabLayout.addOnTabSelectedListener(object : OnTabSelectedListener {
    override fun onTabSelected(tab: TabLayout.Tab) {
        when(tab.position) {
            // Carry out various Fragment transactions (replacing, swapping, etc)
            // on the fragment container in your activity (see section 6.3)
            0 -> ...
            1 -> ...
        }
    }

    override fun onTabUnselected(tab: TabLayout.Tab) {}
    override fun onTabReselected(tab: TabLayout.Tab) {}
})
```
