Android Kotlin: How to add padding to ActionBar title left side

Adding Padding to ActionBar Title (Kotlin)

This code demonstrates how to add left-side padding to the title displayed in the Android ActionBar using Kotlin. The approach involves creating a custom TextView and setting it as the action bar's custom view.

Breakdown and Explanation:

  1. MainActivity Setup:

    • The MainActivity class inherits from AppCompatActivity.
    • It defines a context variable to hold the activity reference.
    • In onCreate, the layout (activity_main.xml) is inflated and the context is retrieved.
  2. Customizing the ActionBar:

    • The code checks if the supportActionBar is available.
    • It creates a custom TextView using the actionBarCustomTitle method.
    • This TextView is then set as the customView of the action bar using supportActionBar?.customView.
    • To add padding, the setPadding method is called on the customView. Here, only left padding of 30dp is set.
    • Finally, additional action bar settings like enabling the home button, logo, and setting a custom logo are applied.
  3. Creating Custom Title View:

    • The actionBarCustomTitle method creates a TextView.
    • It sets the text for the title, initializes layout parameters (wrapping content for both width and height), and applies them to the TextView.
    • The text appearance is set to the default action bar title style (TextAppearance_Material_Widget_ActionBar_Title) and the text color is set to white.
  4. Converting Values to dp:

    • An extension method toDp is defined to convert integer values into density-independent pixels (dp) based on the context's display metrics.

Summary

This code provides a flexible way to customize the ActionBar title in your Android app using Kotlin. By creating a custom TextView and setting it as the action bar's view, you can control various aspects of the title's appearance, including adding padding for better visual alignment or spacing. The code also demonstrates the use of an extension method for easy conversion to dp units.


MainActivity.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.util.TypedValue
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


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


            // Set action bar title left padding
            // Space between action bar logo and title
            customView.setPadding(
                30.toDp(context), // left padding
                0, // top padding
                0, // right padding
                0 // bottom padding
            )


            // 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 = "Title Padding Left 30 Dp"


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

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


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



// Extension method to convert values to dp
fun Int.toDp(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,
    this.toFloat(),
    context.resources.displayMetrics
).toInt()
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