TabLayout in Android with Kotlin





1. Create New Project:

           Lets create New Project with Kotlin support as follows:


2. Adding design library:

          Add design library in app's build.gradle file.

build.gradle

        implementation 'com.android.support:design:26.1.0'


3. Drawing layouts:


  •  Create a layout with TabLayout and ViewPager

slide_page.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout      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">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent">

        <android.support.design.widget.TabLayout
            android:id="@+id/tabLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            app:elevation="4dp"
            app:tabIndicatorColor="@color/white"
            app:tabMode="fixed"
            app:tabSelectedTextColor="@color/white"
            app:tabTextColor="@color/grey" />

        <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>


  • Design layout to show up in Fragments

fragment_page.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <TextView
        android:id="@+id/info_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

4. Resources:

          Other resources to be included.

strings.xml

<resources>
    <string name="app_name">SlidingTab Demo</string>
    <string name="first_fragment">First Fragment</string>
    <string name="second_fragment">Second Fragment</string>
</resources>

colors.xml

<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>
    <color name="grey">#e8e8e8</color>
    <color name="white">#ffffff</color>
</resources>

5. Code

                Let's proceed with code now.

  • Create adapter for ViewPager. In Kotlin, traditional 'switch' functional block in java, will work as 'when' block. 
          Syntax:

                when ([variable]){
                           [value0] -> {
                                              ---  //code to be executed
                                              ---
                                             }

                          [value1] -> {
                                              ---  //code to be executed
                                              ---
                                             }
                 }

SlidingPagerAdapter.kt

class SlidingPagerAdapter(fragmentManager: FragmentManager?) : FragmentPagerAdapter(fragmentManager) {

    private val TITLES = arrayOf("TAB 1", "TAB 2")
    override fun getItem(position: Int): Fragment {
        when (position) {
            0 -> {
                println("position 0");
                return FirstFragment()
            }

            1 -> {
                println("position 1");
                return SecondFragment()
            }
            else ->
                return FirstFragment()

        }
    }

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

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

}


  • Then create Fragments

FirstFragment.kt

class FirstFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.fragment_page, container, false);
    }

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

        infoText.text = getString(R.string.first_fragment)

    }
}

SecondFragment.kt

class SecondFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater!!.inflate(R.layout.fragment_page, container, false);
    }

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

        infoText.text = getString(R.string.second_fragment)

    }
}


  • Create an activity for the TabLayout to be displayed.

SlidingTabActivity.kt

class SlidingTabActivity : AppCompatActivity() {

    lateinit var adapter: SlidingPagerAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.slide_page)
    
        adapter = SlidingPagerAdapter(supportFragmentManager)
        viewPager.adapter = adapter

        viewPager.offscreenPageLimit = 1


        tabLayout.setupWithViewPager(viewPager)
        tabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

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

            override fun onTabSelected(tab: TabLayout.Tab?) {
                viewPager.currentItem = tab!!.position
            }

        })

    }
}

6. Run Application:

             Now its ready for Output.







Comments

Popular posts from this blog

Retrofit Integration in Android - Kotlin

SOAP Client using ksoap2 in Android - Kotlin

Using Camera in Android - Kotlin

Room with LiveData, ViewModel - Android Architecture Components - Kotlin

Map, Location update and AutoComplete Places - Kotlin

RecyclerView with different number of columns using SpanSizeLookup

Exploring Android Navigation Architecture Component - MVVM - Kotlin

Exploring Android Slices - JetPack

FCM Integration in Android - Kotlin

Stripe Integration in Android - Kotlin