Saturday, June 13, 2020

android kotlin - ActionBar title center

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() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        
        supportActionBar?.apply {
            // Show custom title in action bar
            customView = actionBarCustomTitle()
            displayOptions = DISPLAY_SHOW_CUSTOM

            setDisplayShowHomeEnabled(true)
            setDisplayUseLogoEnabled(true)
            setLogo(R.drawable.ic_action_help)
        }
    }


    
    // Function to create a custom action bar title
    private fun actionBarCustomTitle():TextView{
        return TextView(this).apply {
            // Set the action bar title text
            text = "ActionBar Center Title"

            
            // Create a layout params instance
            val params = LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT
            )

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

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

            
            // Set the text appearance of action bar title text
            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" />