Android – How to get the ActionBar height

androidandroid-actionbar

I am trying to get the height of the ActionBar (using Sherlock) every time an activity is created (specially to handle configuration changes on rotation where the ActionBar height might change).

For this I use the method ActionBar.getHeight() which works only when the ActionBar is shown.

When the first activity is created for the first time, I can call getHeight() in the onCreateOptionsMenu callback. But this method is not called after.

So my question is when can I call getHeight() and be assured that it doesn't return 0?
Or if it is not possible, how can I set the height of the ActionBar ?

Best Answer

While @birdy's answer is an option if you want to explicitly control the ActionBar size, there is a way to pull it up without locking the size that I found in support documentation. It's a little awkward but it's worked for me. You'll need a context, this example would be valid in an Activity.

// Calculate ActionBar height
TypedValue tv = new TypedValue();
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
{
    int actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
}

Kotlin:

val tv = TypedValue()
if (requireActivity().theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
    val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
}