Tuesday, June 16, 2020

android kotlin - ActionBar background color programmatically

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.graphics.drawable.GradientDrawable
import android.os.Bundle
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 {
            title = "ActionBar background color"


            // Set action bar background color
            setBackgroundDrawable(
                ColorDrawable(
                    Color.parseColor("#8FBC8F")
                )
            )


            // We can also show gradient background in action bar
            // Uncomment below line to see gradient background
            //setBackgroundDrawable(gradientDrawable())
        }
    }
}



// Method to generate gradient drawable
private fun gradientDrawable(): GradientDrawable {
    return GradientDrawable().apply {
        colors = intArrayOf(
            Color.parseColor("#F0FFFF"),
            Color.parseColor("#00BFFF"),
            Color.parseColor("#89CFF0")
        )
        gradientType = GradientDrawable.LINEAR_GRADIENT
        shape = GradientDrawable.RECTANGLE
        setStroke(2,Color.parseColor("#2A52BE"))
    }
}
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" />