Monday, June 15, 2020

android kotlin - ActionBar title text size

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.AbsoluteSizeSpan
import android.text.style.RelativeSizeSpan
import androidx.appcompat.app.AppCompatActivity


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


        // If the support action bar is available
        supportActionBar?.apply {
            // Text for Action bar title
            val titleText = "  ActionBar Title Spannable"


            // Initialize a Spannable string instance
            val spannableString = SpannableString(titleText)

            // Scale title text size relative to original size
            // Increase title text size / font size
            val relativeSizeSpan = RelativeSizeSpan(1.2F)

            spannableString.setSpan(
                relativeSizeSpan,
                0,
                titleText.length,
                Spannable.SPAN_INCLUSIVE_EXCLUSIVE
            )

            // Show spannable title on action bar
            title = spannableString


            // Another way to change title text size
            val anotherTitle = "  Title By Absolute Size Span"
            val anotherSpannableSting = SpannableString(anotherTitle)

            // Absolute size span
            val absoluteSizeSpan = AbsoluteSizeSpan(
                14, // size in dip
                true // dip true
            )

            anotherSpannableSting.setSpan(
                absoluteSizeSpan,
                0,
                anotherSpannableSting.length,
                Spannable.SPAN_INCLUSIVE_INCLUSIVE
            )

            // Comment and uncomment below line to test the effect
            //title = anotherSpannableSting


            // Show logo on action bar
            setDisplayShowHomeEnabled(true)
            setDisplayUseLogoEnabled(true)
            setLogo(R.drawable.ic_action_help)
        }
    }
}
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" />