Android Kotlin: ActionBar title click listener

This code demonstrates how to implement a click listener to an ActionBar title in an Android Activity.

The onCreate method of the MainActivity class is where the majority of the code resides. Here's a step-by-step breakdown of the process:

  1. Get the Context:

    • The line context = this retrieves the context of the current activity and stores it in a variable named context.
  2. Initialize a Counter:

    • An integer variable named counter is initialized to 0. This variable will be used to track the number of times the ActionBar title is clicked.
  3. Set Up the ActionBar:

    • The supportActionBar?.apply block checks if the ActionBar is available and then applies a series of configurations to it:
      • A custom view is set as the ActionBar title using the customView property. The actionBarCustomTitle() method is responsible for creating this custom view.
      • An onClickListener is set on the custom view. Whenever the user clicks on the ActionBar title, the code within the onClickListener block will be executed.
      • The displayOptions property is set to DISPLAY_SHOW_CUSTOM to indicate that a custom view is being used as the ActionBar title.
      • The setDisplayShowHomeEnabled property is set to true to display the home icon in the ActionBar.
      • The setDisplayUseLogoEnabled property is set to true to display the app's logo in the ActionBar.
      • The setLogo method is used to set the drawable resource for the ActionBar logo.
  4. Create a Custom Title for the ActionBar:

    • The actionBarCustomTitle() method is responsible for creating a custom TextView that will be used as the ActionBar title. Here's a breakdown of the steps involved:
      • A new TextView is created by calling the constructor TextView(context).
      • The text of the TextView is set to "ActionBar Click Listener" using the text property.
      • A new LayoutParams object is created to define the layout parameters of the TextView. The layout parameters specify that the TextView should match the parent's width (i.e., MATCH_PARENT) and wrap its content height (i.e., WRAP_CONTENT). These layout parameters are then applied to the TextView using the layoutParams property.
      • The text gravity of the TextView is set to CENTER to center the text horizontally within the ActionBar title.
      • The text appearance of the TextView is set to textAppearance_Material_Widget_ActionBar_Title using the setTextAppearance method. This ensures that the text follows the default styling for ActionBar titles in Material Design.
      • The text color of the TextView is set to white using the setTextColor method.

In Summary:

By following these steps, this code effectively implements a click listener on the ActionBar title, allowing users to interact with the title and perform actions based on their clicks. The use of a custom TextView provides more control over the appearance and behavior of the ActionBar title compared to using the default title functionality.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.widget.TextView
import androidx.appcompat.app.ActionBar.DISPLAY_SHOW_CUSTOM
import androidx.appcompat.app.AppCompatActivity
import androidx.constraintlayout.widget.ConstraintLayout.LayoutParams


class MainActivity : AppCompatActivity() {
    lateinit var context:MainActivity

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

        // Get the context
        context = this

        // Initialize a counter variable
        var counter = 0;


        // If the support action bar is available
        supportActionBar?.apply {
            // Show custom title in action bar
            customView = actionBarCustomTitle()


            // Action bar title click listener
            customView.setOnClickListener {
                counter++
                (it as TextView).text =
                    "Title clicked $counter time(s)"
            }


            // More action bar settings
            displayOptions = DISPLAY_SHOW_CUSTOM
            setDisplayShowHomeEnabled(true)
            setDisplayUseLogoEnabled(true)
            setLogo(R.drawable.ic_action_help)
        }
    }



    // Method to create a custom title for action bar
    private fun actionBarCustomTitle():TextView{
        return TextView(context).apply {
            // Set action bar title text
            text = "ActionBar Click Listener"


            // Initialize the layout params instance
            val params = LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT
            )

            // Apply the layout parameters to the text view
            layoutParams = params


            // Center align the text view/ action bar title
            gravity = Gravity.CENTER


            // Set the action bar title text appearance
            setTextAppearance(
                android.R.style
                    .TextAppearance_Material_Widget_ActionBar_Title
            )


            // Set the action bar title text color
            setTextColor(Color.WHITE)
        }
    }
}
activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC" />
More android kotlin tutorials