android kotlin - Get ActionBar height

MainActivity.kt

package com.cfsuman.kotlintutorials

import android.content.Context
import android.os.Bundle
import android.util.DisplayMetrics
import android.util.TypedValue
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity


class MainActivity : AppCompatActivity() {
    lateinit var context:MainActivity

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

        // Get the widgets reference from XML layout
        val textView: TextView = findViewById(R.id.textView)

        // Get the context
        context = this


        // Get action bar height in pixels
        val typedValue = TypedValue()

        if (this.theme.resolveAttribute(
                android.R.attr.actionBarSize,
                typedValue,
                true
            )){
            val actionBarHeightInPixels = TypedValue
                .complexToDimensionPixelSize(
                    typedValue.data,
                    resources.displayMetrics
            )

            val actionBarHeightInDp = actionBarHeightInPixels
                .pixelsToDpInt(context)

            textView.apply {
                text = "ActionBar Height\n\n"
                append("$actionBarHeightInPixels Pixels")
                append("\n$actionBarHeightInDp DP")
            }
        }
    }
}



// Extension function to convert pixels value to dp value
// This method return integer dp value
fun Int.pixelsToDpInt(context: Context):Int{
    return this / (context.resources
        .displayMetrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT)
}
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"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/rootLayout"
    android:background="#DCDCDC">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:fontFamily="sans-serif"
        android:gravity="center"
        android:textStyle="bold"
        android:textSize="24sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="TextView" />

</androidx.constraintlayout.widget.ConstraintLayout>
More android kotlin tutorials