Android Material Design Tabs (Tab Layout) with Swipe | Basic

Hello, friends, I am here with another android tutorial about tab layout or tabs with a swipe gesture.

Tab layout is visible below toolbar with View pager, used to create swipeable views on. Tabs are designed to work with fragments. Use them to swipe fragments in view pager. In this article, we are going to show you how to implement material design tabs in your android app.

After creating a new project open build.gradle and add this dependency and sync project.

    implementation 'com.google.android.material:material:1.0.0'

Add Tab Layout and View Pager in activity_main.xml

<?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">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:minHeight="?actionBarSize"
            android:padding="@dimen/appbar_padding"
            android:text="@string/app_name"
            android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary" />
    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

Create a tabs adapter “SectionPagerAdapter” which extends FragmentPagerAdapter.

SectionPagerAdapter.kt

class SectionsPagerAdapter(fm: FragmentManager) :
    FragmentPagerAdapter(fm) {
    private val arrTitles: ArrayList<String>  = ArrayList<String>()
    private val arrFragments : ArrayList<Fragment>  = ArrayList<Fragment>()

    fun addFragment(title: String, frag: Fragment){
        arrTitles.add(title)
        arrFragments.add(frag)
    }

    override fun getItem(position: Int): Fragment {
        return arrFragments[position]
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return arrTitles[position]
    }

    override fun getCount(): Int {
        return arrFragments.size
    }
}

Create fragment for view pager we will add fragment to adapter

PlaceholderFragment.kt

class PlaceholderFragment : Fragment() {
    

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val root = inflater.inflate(R.layout.fragment_main, container, false)
        val textView: TextView = root.findViewById(R.id.section_label)
       textView.text = "Fragment Index ${arguments?.getInt(ARG_SECTION_NUMBER)}"
        return root
    }

    companion object {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private const val ARG_SECTION_NUMBER = "section_number"

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        @JvmStatic
        fun newInstance(sectionNumber: Int): PlaceholderFragment {
            return PlaceholderFragment().apply {
                arguments = Bundle().apply {
                    putInt(ARG_SECTION_NUMBER, sectionNumber)
                }
            }
        }
    }
}

In placeholder fragment we pass a parameter as the index to show different instances of this fragment in tabs.

we use same fragment here to reduce the complexity and ease of understanding.

Now the main part binding view pager to tab layout and adapter to view pager, inside the onCreate of MainActivity

MainActivity.kt

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val sectionsPagerAdapter = SectionsPagerAdapter(supportFragmentManager)

        /*Adding fragments to tabs*/
        sectionsPagerAdapter.addFragment("Tab 1", PlaceholderFragment.newInstance(1))
        sectionsPagerAdapter.addFragment("Tab 2", PlaceholderFragment.newInstance(2))

        val viewPager: ViewPager = findViewById(R.id.view_pager)
        viewPager.adapter = sectionsPagerAdapter
        val tabs: TabLayout = findViewById(R.id.tabs)
        tabs.setupWithViewPager(viewPager)

    }
}

Output:

Text tabs in android

Some options to customize tabs appearance:
app:tabGravity=”fill” for Navigation tab gravity. Other is center for placing navigation tabs from center
app:tabIndicatorColor=”@color/white” for indicator in tabs. Here you can see white indicator.
app:tabIndicatorHeight=”4dp” for indicator height.
app:tabMode=”fixed” for tab mode. Other is scrollable for many more tabs.
app:tabTextColor=”@color/semi_yellow” for unselected tab text color.
app:tabSelectedTextColor=”@color/yellow” for selected tab text color.

If you want to add icons to tab, you have to do is call setIcon() method of tab. Create icon array and assign each one for each tab like this:

private int[] tabIcons = {
 R.drawable.home,
 R.drawable.notification,
 R.drawable.star
};
tabLayout.getTabAt(0).setIcon(tabIcons[0]);
tabLayout.getTabAt(1).setIcon(tabIcons[1]);
tabLayout.getTabAt(2).setIcon(tabIcons[2]);

Get full code on Github

Leave a Reply