Tablayout Android Kotlin With Different Actionbar/Toolbar MenuItems For Different Fragments

tablayout android kotlin

This is a tablayout android kotlin example.

Tablayout android kotlin tutorial will guide you to make different actionbar/toolbar menuitems for different colors.

In whatsapp, when you slide fragments menu items are also changing.

We will develop this functionality in tablayout android tutorial.

If you don’t have go through basic tablayout tutorial, then visit android tablayout kotlin tutorial.

Develop basic tablayout example from above link then follow steps of this tutorial.

First, check the output of this example.

Download Source Code for Tablayout Android Kotlin example

[sociallocker]Download KotlinTabMenuItem[/sociallocker]

Step 1: Make Basic structure

Follow all the steps from basic tablayout Android tutorial.

After you have completed above tutorial, you will have one android project with tablayout.

Now follow below steps.

Step 2: Adding images to drawable

Download images and copy them into “drawable” directory

TabMenu Icons

Step 3: Updating styles.xml

Update styles.xml file as per below source code

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

</resources>

Step 4: Creating toolbar.xml file

Create a new resource file named toolbar.xml and paste below

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Step 5: Developing OneActivity

Create a new activity named “OneActivity.kt

Copy following in activity_one.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.exampledemo.parsaniahardik.tabmenuitem.OneActivity">

    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:background="#f12a1f"
        android:textSize="25sp"
        android:textColor="#fff"
        android:text="This is One Activity. Similarly you can create activity for two and three fragments." />

</LinearLayout>

Add following source code into OneActivity.kt class

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v7.widget.Toolbar
import android.view.MenuItem

class OneActivity : AppCompatActivity() {

    private var toolbar: Toolbar? = null

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

        toolbar = findViewById(R.id.toolbar) as Toolbar
        setSupportActionBar(toolbar)
        supportActionBar!!.title = "One Activity"
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)

    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            onBackPressed()
            return true
        }
        return false
    }
}

Step 6: Creating menu resource directory

Create a new resource directory named “menu” inside the “res” directory.

Inside “menu,” make three new xml files and name them as one_menu.xml,two_menu.xml and three_menu.xml

Add below source code in one_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_message"
        android:orderInCategory="100"
        android:title="Message"
        android:icon="@drawable/message"
        app:showAsAction="always" />

</menu>

Add following in two_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_car"
        android:orderInCategory="100"
        android:title="Message"
        android:icon="@drawable/car"
        app:showAsAction="always" />

</menu>

Add below in three_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <item
        android:id="@+id/action_logout"
        android:orderInCategory="100"
        android:title="Logout"
        app:showAsAction="never" />


</menu>

Step 7: Updating all fragments

Update OneFragment.kt as per below code

/**
 * Created by Parsania Hardik on 27-Jan-18.
 */
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast


class OneFragment : Fragment() {

    private var view1: View? = null
    private var textView: TextView? = null

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

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

        textView = view1!!.findViewById(R.id.tv) as TextView

        textView!!.setOnClickListener {
            val intent = Intent(activity, OneActivity::class.java)
            startActivity(intent)
        }

        return view1
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {

        inflater!!.inflate(R.menu.one_menu, menu)

        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item!!.itemId


        if (id == R.id.action_message) {
            Toast.makeText(activity, "Message clicked!", Toast.LENGTH_SHORT).show()
            return true

        }

        return super.onOptionsItemSelected(item)
    }

}

Update TwoFragment.kt as per following

/**
 * Created by Parsania Hardik on 27-Jan-18.
 */
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast


class TwoFragment : Fragment() {

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

    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)
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {

        inflater!!.inflate(R.menu.two_menu, menu)

        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item!!.itemId


        if (id == R.id.action_car) {
            Toast.makeText(activity, "Car clicked!", Toast.LENGTH_SHORT).show()
            return true

        }

        return super.onOptionsItemSelected(item)
    }
}

Update ThreeFragment.kt like below

/**
 * Created by Parsania Hardik on 27-Jan-18.
 */
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.Menu
import android.view.MenuInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.Toast

class ThreeFragment : Fragment() {

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

    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)
    }

    override fun onCreateOptionsMenu(menu: Menu?, inflater: MenuInflater?) {

        inflater!!.inflate(R.menu.three_menu, menu)

        super.onCreateOptionsMenu(menu, inflater)
    }

    override fun onOptionsItemSelected(item: MenuItem?): Boolean {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        val id = item!!.itemId


        if (id == R.id.action_logout) {
            Toast.makeText(activity, "Logout clicked!", Toast.LENGTH_SHORT).show()
            return true

        }

        return super.onOptionsItemSelected(item)
    }
}

Java Version

Java version of this tutorial: Tablayout Android

Above tutorial will helpful if you are not familiar with kotlin.

Use comment section for queries and reviews. Thank you.