Reader small image

You're reading from  Android Studio 4.1 Development Essentials – Kotlin Edition

Product typeBook
Published inMay 2021
PublisherPackt
ISBN-139781801815987
Edition1st Edition
Right arrow
Author (1)
Neil Smyth
Neil Smyth
author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth

Right arrow

53. Creating a Tabbed Interface using the TabLayout Component

The previous chapter outlined the concept of material design in Android and introduced two of the components provided by the design support library in the form of the floating action button and the Snackbar. This chapter will demonstrate how to use another of the design library components, the TabLayout, which can be combined with the ViewPager class to create a tab based interface within an Android activity.

53.1 An Introduction to the ViewPager

Although not part of the design support library, the ViewPager is a useful companion class when used in conjunction with the TabLayout component to implement a tabbed user interface. The primary role of the ViewPager is to allow the user to flip through different pages of information where each page is most typically represented by a layout fragment. The fragments that are associated with the ViewPager are managed by an instance of the FragmentPagerAdapter class.

At a minimum the pager adapter assigned to a ViewPager must implement two methods. The first, named getCount(), must return the total number of page fragments available to be displayed to the user. The second method, getItem(), is passed a page number and must return the corresponding fragment object ready to be presented to the user.

53.2 An Overview of the TabLayout Component

As previously discussed, TabLayout is one of the components introduced as part of material design and is included in the design support library. The purpose of the TabLayout is to present the user with a row of tabs which can be selected to display different pages to the user. The tabs can be fixed or scrollable, whereby the user can swipe left or right to view more tabs than will currently fit on the display. The information displayed on a tab can be text-based, an image or a combination of text and images. Figure 53-1, for example, shows the tab bar for an app consisting of four tabs displaying images:

Figure 53-1

Figure 53-2, on the other hand, shows a TabLayout configuration consisting of four tabs displaying text in a scrollable configuration:

Figure 53-2

The remainder of this chapter will work through the creation of an example project that demonstrates the use of the TabLayout component together with a ViewPager...

53.3 Creating the TabLayoutDemo Project

Select the Create New Project quick start option from the welcome screen and, within the resulting new project dialog, choose the Basic Activity template before clicking on the Next button.

Enter TabLayoutDemo into the Name field and specify com.ebookfrenzy.tablayoutdemo as the package name. Before clicking on the Finish button, change the Minimum API level setting to API 26: Android 8.0 (Oreo) and the Language menu to Kotlin.

Locate and open the app -> Gradle Scripts - > build.gradle (Module: TabLayoutDemo.app) file in the project tool window and modify the plugins section so that reads as follows before clicking the Sync Now link in the toolbar to commit the change:

plugins {

    id 'com.android.application

    id 'kotlin-android'

    id 'kotlin-android-extensions'

}

Once the project has been created, load the content_main.xml...

53.4 Creating the First Fragment

Each of the tabs on the TabLayout will display a different fragment when selected. Create the first of these fragments by right-clicking on the app -> java -> com.ebookfrenzy.tablayoutdemo entry in the Project tool window and selecting the New -> Fragment -> Fragment (Blank) option. In the resulting dialog, enter Tab1Fragment into the Fragment Name: field and fragment_tab1 into the Fragment Layout Name: field. Click on the Finish button to create the new fragment:

Figure 53-3

Edit the Tab1Fragment.kt file and, if Android Studio has not added one automatically, add an OnFragmentInteractionListener interface declaration as follows:

.

.

import android.net.Uri

.

.

    interface OnFragmentInteractionListener {

        fun onFragmentInteraction(uri: Uri)

    }

.

.

Load the newly created fragment_tab1.xml file (located under...

53.5 Duplicating the Fragments

So far, the project contains one of the four required fragments. Instead of creating the remaining three fragments using the previous steps it would be quicker to duplicate the first fragment. Each fragment consists of a layout XML file and a Kotlin class file, each of which needs to be duplicated.

Right-click on the fragment_tab1.xml file in the Project tool window and select the Copy option from the resulting menu. Right-click on the layout entry, this time selecting the Paste option. In the resulting dialog, name the new layout file fragment_tab2.xml before clicking the OK button. Edit the new fragment_tab2.xml file and change the text on the Text View to “Tab 2 Fragment”, following the usual steps to extract the string to a resource named tab_2_fragment.

To duplicate the Tab1Fragment class file, right-click on the class listed under app -> java -> com.ebookfrenzy.tablayoutdemo and select Copy. Right-click on the com.ebookfrenzy...

53.6 Adding the TabLayout and ViewPager

With the fragment creation process now complete, the next step is to add the TabLayout and ViewPager to the main activity layout file. Edit the activity_main.xml file and add these elements as outlined in the following XML listing. Note that the TabLayout component is embedded into the AppBarLayout element while the ViewPager is placed after the AppBarLayout:

<?xml version="1.0" encoding="utf-8"?>

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    tools:context=".MainActivity">

 ...

53.7 Creating the Pager Adapter

This example will use the ViewPager approach to handling the fragments assigned to the TabLayout tabs. With the ViewPager added to the layout resource file, a new class which subclasses FragmentPagerAdapter needs to be added to the project to manage the fragments that will be displayed when the tab items are selected by the user.

Add a new class to the project by right-clicking on the com.ebookfrenzy.tablayoutdemo entry in the Project tool window and selecting the New -> Kotlin File/Class menu option. In the new class dialog, enter TabPagerAdapter into the Name: field, select the Class item in the list and press the keyboard Return key.

Edit the TabPagerAdapter.kt file so that it reads as follows:

package com.ebookfrenzy.tablayoutdemo

 

import androidx.fragment.app.Fragment

import androidx.fragment.app.FragmentManager

import androidx.fragment.app.FragmentPagerAdapter

 

class TabPagerAdapter(fm: FragmentManager...

53.8 Performing the Initialization Tasks

The remaining tasks involve initializing the TabLayout, ViewPager and TabPagerAdapter instances and declaring the main activity class as implementing fragment interaction listeners for each of the four tab fragments. Edit the MainActivity.kt file so that it reads as follows:

package com.ebookfrenzy.tablayoutdemo

 

import android.os.Bundle

import com.google.android.material.snackbar.Snackbar

import androidx.appcompat.app.AppCompatActivity

import android.view.Menu

import android.view.MenuItem

import com.google.android.material.tabs.TabLayout

import android.net.Uri

 

import kotlinx.android.synthetic.main.activity_main.*

 

class MainActivity : AppCompatActivity(),

           Tab1Fragment.OnFragmentInteractionListener,

           Tab2Fragment.OnFragmentInteractionListener,

...

53.9 Testing the Application

Compile and run the app on a device or emulator and make sure that selecting a tab causes the corresponding fragment to appear in the content area of the screen:

Figure 53-6

53.10 Customizing the TabLayout

The TabLayout in this example project is configured using fixed mode. This mode works well for a limited number of tabs with short titles. A greater number of tabs or longer titles can quickly become a problem when using fixed mode as illustrated by Figure 53-6:

Figure 53-7

In an effort to fit the tabs into the available display width the TabLayout has used multiple lines of text. Even so, the second line is clearly truncated making it impossible to see the full title. The best solution to this problem is to switch the TabLayout to scrollable mode. In this mode the titles appear in full length, single line format allowing the user to swipe to scroll horizontally through the available items as demonstrated in Figure 53-7:

Figure 53-8

To switch a TabLayout to scrollable mode, simply change the app:tabMode property in the activity_main.xml layout resource file from “fixed” to “scrollable”:

<android.support...

53.11 Displaying Icon Tab Items

The last step in this tutorial is to replace the text based tabs with icons. Achieve this by modifying the onCreate() method in the MainActivity.kt file to assign some built-in drawable icons to the tab items:

private fun configureTabLayout() {

 

 tab_layout.addTab(tab_layout.newTab().setIcon(

            android.R.drawable.ic_dialog_email))

    tab_layout.addTab(tab_layout.newTab().setIcon(

            android.R.drawable.ic_dialog_dialer))

    tab_layout.addTab(tab_layout.newTab().setIcon(

            android.R.drawable.ic_dialog_map))

    tab_layout.addTab(tab_layout.newTab().setIcon(

            android.R.drawable...

53.12 Summary

TabLayout is one of the components introduced as part of the Android material design implementation. The purpose of the TabLayout component is to present a series of tab items which, when selected, display different content to the user. The tab items can display text, images or a combination of both. When combined with the ViewPager class and fragments, tab layouts can be created with relative ease, with each tab item selection displaying a different fragment.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Android Studio 4.1 Development Essentials – Kotlin Edition
Published in: May 2021Publisher: PacktISBN-13: 9781801815987
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at £13.99/month. Cancel anytime

Author (1)

author image
Neil Smyth

Neil Smyth has over 25 years of experience in the IT industry, including roles in software development and enterprise-level UNIX and Linux system administration. In addition to a bachelor’s degree in information technology, he also holds A+, Security+, Network+, Project+, and Microsoft Certified Professional certifications and is a CIW Database Design Specialist. Neil is the co-founder and CEO of Payload Media, Inc. (a technical content publishing company), and the author of the Essentials range of programming and system administration books.
Read more about Neil Smyth