Introduction
This code snippet demonstrates how to set the elevation of a toolbar programmatically in an Android application developed using Kotlin. The toolbar elevation refers to the casting of a shadow beneath the toolbar, providing a 3D effect and enhancing the visual hierarchy of the app's UI.
Breakdown of the Code
MainActivity.kt
- This file represents the main activity class that manages the lifecycle and behavior of the app.
 - The 
onCreatefunction is called when the activity is first created.- It sets the layout of the activity using 
setContentView(R.layout.activity_main). - The 
setSupportActionBar(toolbar)line configures the toolbar as the action bar for the activity. - The 
supportActionBar?.applyblock applies customizations to the action bar:- Sets the title of the action bar to 'Kotlin - Toolbar Add Elevation'.
 - Sets the elevation of the toolbar using the 
elevationproperty. The value is obtained by calling thetoDpextension function and converting 4dp to pixels based on the device's display metrics. 
 
 - It sets the layout of the activity using 
 
toDp Extension Function (MainActivity.kt)
- This extension function is defined within the MainActivity class.
 - It converts a given integer value (in dp) to pixels.
 - It utilizes the 
TypedValue.applyDimensionmethod, which performs the unit conversion based on the display metrics of the context (activity in this case). 
activity_main.xml
- This file defines the layout of the main activity screen in XML format.
 - The 
androidx.appcompat.widget.Toolbarelement represents the toolbar component.- The 
android:elevationattribute is set to 4dp to provide a basic elevation to the toolbar from the layout itself. - Other attributes like 
android:id,android:layout_width, andandroid:layout_heightdefine the toolbar's properties. 
 - The 
 
res/values/styles.xml
- This file stores the app's theming configurations.
 - The 
AppThemestyle inherits fromTheme.MaterialComponents.Light.NoActionBar. - It can be customized by adding attributes like 
colorPrimary,colorPrimaryDark, andcolorAccentto define the app's color scheme. 
Summary
This code effectively demonstrates setting the toolbar elevation in Kotlin for an Android application. It leverages an extension function for unit conversion and allows programmatic control over the toolbar's appearance, enhancing the app's UI design and user experience.
Additional Notes
The code snippet also includes an extension function toDp that converts dp values to pixels. This is a useful utility function that can be used throughout your Android development projects.
package com.example.jetpack
import android.content.Context
import android.os.Bundle
import android.util.TypedValue
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // set toolbar as support action bar
        setSupportActionBar(toolbar)
        supportActionBar?.apply {
            title = "Kotlin - Toolbar Add Elevation"
            // we can add toolbar elevation programmatically
            // default elevation 4dp
            elevation = 4.toDp(this@MainActivity).toFloat()
        }
    }
}
// extension method to convert values to dp
fun Int.toDp(context: Context):Int = TypedValue.applyDimension(
    TypedValue.COMPLEX_UNIT_DIP,this.toFloat(),context.resources.displayMetrics
).toInt()
<?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"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#C5C4BB"
    tools:context=".MainActivity">
    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="?attr/actionBarTheme"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:elevation="4dp"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>
</resources>