Android Tablayout Kotlin With Fragments,ViewPager,Material Design

android tablayout kotlin

Whatsapp is using Android Tablayout Kotlin for basic navigation.

In today’s Android Tablayout Kotlin example, we will develop that kind of structure programmatically.

Android Tablayout Kotlin uses fragments, material design and view pager as basic components.

You will be able to make a project where user can swipe left or right to switch between tabs.

This method is used by whatsapp also.

First, watch the output, then we will prepare it.

Download Source Code for android tablayout kotlin example

[sociallocker]Download Kotlin_SimpleTabs[/sociallocker]

Step 1: Create a new project in Android Studio.

Consider empty activity as a main activity when you create a fresh new project in android studio.

Step 2: Update build.gradle(Module:app) file

Add below in build.gradle(Module:app) file

compile 'com.android.support:design:26.0.1'
compile 'com.android.support:support-v4:26.0.1'

Above two lines will give access to necessary classes to use material design in our app.

Whole source code for build.gradle(Module:app)

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.example.parsaniahardik.kotlin_simpletabs"
        minSdkVersion 15
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation"org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation 'com.android.support:appcompat-v7:26.0.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'

    compile 'com.android.support:design:26.0.1'
    compile 'com.android.support:support-v4:26.0.1'
}

Step 3: Updating colors.xml

Go to the res->values->colors.xml directory

update colors.xml as below

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#ca9e2d</color>
    <color name="colorPrimaryDark">#d6b153</color>
    <color name="colorAccent">#fff</color>
</resources>

Step 4: Preparing three fragments

Now we need to make fragment per each tabs.

Means that if you want three tabs than make three fragments, if you want five tabs than make five fragments.

We will add three tabs in this tutorial.

You can update the look and feel of every tab by adding required code to their fragment’s xml or .kt files.

Create three fragments and give them name as “OneFragment,” “TwoFragment,” and “ThreeFragment.

Add below code in fragment_one.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="#8cf11f"
        android:textSize="25sp"
        android:textColor="#fff"
        android:text="1. One" />

</FrameLayout>

Add following in OneFragment.kt

/**
 * Created by Parsania Hardik on 20-Jan-18.
 */
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.example.parsaniahardik.kotlin_simpletabs.R

class OneFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater!!.inflate(R.layout.fragment_one, container, false)
    }
}

Copy below source code in fragment_two.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="25sp"
        android:background="#5824dc"
        android:textColor="#fff"
        android:text="2. Two" />

</FrameLayout>

Copy following code in TwoFragment.kt

/**
 * Created by Parsania Hardik on 20-Jan-18.
 */
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup


class TwoFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater!!.inflate(R.layout.fragment_two, container, false)
    }

}

Add below code in fragment_three.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- TODO: Update blank fragment layout -->
    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:textSize="25sp"
        android:background="#ec3289"
        android:textColor="#fff"
        android:text="3. Three" />

</FrameLayout>

Paste below code in ThreeFragment.kt

/**
 * Created by Parsania Hardik on 20-Jan-18.
 */
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup


class ThreeFragment : Fragment() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        return inflater!!.inflate(R.layout.fragment_three, container, false)
    }
}

Step 5: Updating MainActivity

update activity_main.xml as below

<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabTextColor="#fff"
            app:tabSelectedTextColor="#000"
            app:tabGravity="fill"
            app:tabMode="fixed" />

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>




Update MainActivity.kt as per following

import android.support.design.widget.TabLayout
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import java.util.ArrayList

class MainActivity : AppCompatActivity() {

    private var tabLayout: TabLayout? = null
    var viewPager: ViewPager? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        viewPager = findViewById(R.id.viewpager) as ViewPager
        setupViewPager(viewPager!!)

        tabLayout = findViewById(R.id.tabs) as TabLayout
        tabLayout!!.setupWithViewPager(viewPager)

    }

    private fun setupViewPager(viewPager: ViewPager) {
        val adapter = ViewPagerAdapter(supportFragmentManager)
        adapter.addFragment(OneFragment(), "ONE")
        adapter.addFragment(TwoFragment(), "TWO")
        adapter.addFragment(ThreeFragment(), "THREE")
        viewPager.adapter = adapter
    }

    internal inner class ViewPagerAdapter(manager: FragmentManager) : FragmentPagerAdapter(manager) {
        private val mFragmentList = ArrayList<Fragment>()
        private val mFragmentTitleList = ArrayList<String>()

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

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

        fun addFragment(fragment: Fragment, title: String) {
            mFragmentList.add(fragment)
            mFragmentTitleList.add(title)
        }

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

Java Version

Java Version of this tutorial : Android TabLayout

That is all for Android tablayout Kotlin example.

If you like this tutorial then please share it in your social media.

Comment if you have queries or a review. Thank you for reading.