Sunday, June 14, 2020

android kotlin - ActionBar title color

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.os.Bundle
import android.text.Spannable
import android.text.SpannableString
import android.text.style.ForegroundColorSpan
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 {
            // Set title text for action bar
            val titleText = "  ActionBar Colored Title"


            // Foreground color span to show colored title text
            val foregroundColorSpan = ForegroundColorSpan(
                Color.YELLOW)

            val spannableString = SpannableString(titleText)

            spannableString.setSpan(
                foregroundColorSpan,
                0,
                titleText.length,
                Spannable.SPAN_INCLUSIVE_INCLUSIVE
            )

            // Show colored title on action bar
            title = spannableString


            // 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" />