Sunday, June 14, 2020

android kotlin - ActionBar title style

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.graphics.Paint
import android.graphics.Typeface
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


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

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



    // Method generate custom view for action bar title
    private fun actionBarCustomView():TextView{
        return TextView(context).apply {
            // Action bar title text
            text = "ActionBar Title Style"


            // Initialize layout parameters for text view
            val params = LayoutParams(
                LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT
            )

            // Apply layout params for text view
            layoutParams = params


            // Center align the text
            gravity = Gravity.CENTER


            // Title text appearance
            setTextAppearance(
                android.R.style
                    .TextAppearance_Material_Widget_ActionBar_Title
            )


            // Action bar title text color
            setTextColor(Color.WHITE)

            // Title font family
            typeface = Typeface.SANS_SERIF


            // Underline the title text
             paintFlags = Paint.UNDERLINE_TEXT_FLAG

            // Bold title text
            // setTypeface(typeface,Typeface.BOLD)

            // Italic title text
            // setTypeface(typeface,Typeface.ITALIC)


            // Bold italic title text
            setTypeface(typeface,Typeface.BOLD_ITALIC)
        }
    }
}
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" />