我试图获得的高度的动作栏(使用夏洛克)每次活动被创建(特别处理配置变化的旋转,其中动作栏的高度可能会改变)。

为此,我使用方法ActionBar. getheight(),它只在显示ActionBar时起作用。

当第一个活动第一次创建时,我可以在onCreateOptionsMenu回调中调用getHeight()。但是之后不会调用此方法。

所以我的问题是,我什么时候可以调用getHeight(),并确保它不返回0? 或者如果不可能,我如何设置动作栏的高度?


当前回答

@Anthony回答适用于支持操作栏的设备,以及那些只支持Sherlock操作栏的设备,必须使用以下方法

    TypedValue tv = new TypedValue();
    if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());

    if(actionBarHeight ==0 && getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true)){
            actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
    }

   //OR as stated by @Marina.Eariel
   TypedValue tv = new TypedValue();
   if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB){
      if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true))
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
   }else if(getTheme().resolveAttribute(com.actionbarsherlock.R.attr.actionBarSize, tv, true){
        actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
   }

其他回答

如果您使用工具栏作为动作栏,

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

然后使用工具栏的layout_height。

int actionBarHeight = toolbar.getLayoutParams().height;

虽然@bird的答案是一个选项,如果你想显式地控制ActionBar的大小,有一种方法可以在不锁定大小的情况下拉起它,我在支持文档中找到了。这有点尴尬,但对我来说很有效。你需要一个上下文,这个例子在一个活动中是有效的。

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

科特林:

val tv = TypedValue()
if (requireActivity().theme.resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
    val actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, resources.displayMetrics)
}
The action bar now enhanced to app bar.So you have to add conditional check for getting height of action bar.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
   height = getActivity().getActionBar().getHeight();
 } else {
  height = ((ActionBarActivity) getActivity()).getSupportActionBar().getHeight();
}

要设置动作栏的高度,你可以创建一个新的主题,就像这样:

<?xml version="1.0" encoding="utf-8"?>
<resources>   
    <style name="Theme.FixedSize" parent="Theme.Sherlock.Light.DarkActionBar">
        <item name="actionBarSize">48dip</item>
        <item name="android:actionBarSize">48dip</item> 
    </style> 
 </resources>

并将此主题设置为您的活动:

android:theme="@style/Theme.FixedSize"

在尝试了所有没有成功的方法之后,我偶然发现了一种实用且非常简单的方法来获得操作栏的默认高度。

仅在API 25和24中测试

C#

Resources.GetDimensionPixelSize(Resource.Dimension.abc_action_bar_default_height_material); 

Java

getResources().getDimensionPixelSize(R.dimen.abc_action_bar_default_height_material);