How to Get ActionBar Height in Pixels in Android?
ActionBar is a UI element that is generally empty but can consist menu and runs on top of the activity. The significance of ActionBar is that it displays the application name and can provide a menu to navigate to the user. The rest of the activity which is programmable is completely separate from the ActionBar. Hence, it is important to know the ActionBar attributes before creating elements into the programmable space. In this article, we will show you how you could get the ActionBar height programmatically in Android. Follow the below steps once the IDE is ready.
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. No additional code is required in the layout (activity_main.xml) file.
XML
<? xml version = "1.0" encoding = "utf-8" ?> < androidx.constraintlayout.widget.ConstraintLayout android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" > < TextView android:layout_width = "wrap_content" android:layout_height = "wrap_content" android:text = "Hello Geek!" app:layout_constraintBottom_toBottomOf = "parent" app:layout_constraintLeft_toLeftOf = "parent" app:layout_constraintRight_toRightOf = "parent" app:layout_constraintTop_toTopOf = "parent" /> </ androidx.constraintlayout.widget.ConstraintLayout > |
Step 3: Working with the MainActivity.kt file (Fetch Action Bar using TypedValue in main code)
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. In this code, we try to resolve the ActionBar height and display it in a Toast message. The displayed value is in Pixels. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.TypedValue import android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super .onCreate(savedInstanceState) setContentView(R.layout.activity_main) val tv = TypedValue() if ( this .theme.resolveAttribute(R.attr.actionBarSize, tv, true )) { val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics) Toast.makeText(applicationContext, actionBarHeight.toString(), Toast.LENGTH_SHORT).show() } } } |
Output:
We can see that we are able to fetch the ActionBar height, which is equal to 147 Pixels.
Please Login to comment...