获得ActionBar的高度

KDe*_*kar 10 android

我在我的应用程序中使用Actionbar.
我以编程方式想要ActionBar的高度因此我正在使用:

ActionBar.getHeight(); 
Run Code Online (Sandbox Code Playgroud)


但是我得到了0的高度值.那么如何才能获得ActionBar的高度?

KDe*_*kar 17

我找到了替代方案ActionBar.getHeight()
如果有人遇到同样的问题,那么这个链接很有用.

虽然如果你想明确控制ActionBar大小,@ birdy的答案是一个选项,有一种方法可以在不锁定我在支持文档中找到的大小的情况下提取它.这有点尴尬,但它对我有用.您需要一个上下文,此示例在Activity中有效.〜安东尼

// Calculate ActionBar's height 
TypedValue tv = new TypedValue(); 
if (getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) {
    actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics()); 
}
Run Code Online (Sandbox Code Playgroud)


Tim*_*ong 5

下面的代码也会有所帮助.您可能需要将getContext()更改为此

final TypedArray styledAttributes = getContext().getTheme().obtainStyledAttributes(
                    new int[] { android.R.attr.actionBarSize });
mActionBarSize = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
Run Code Online (Sandbox Code Playgroud)

答案是从这个问题中复制的ActionBar的大小是多少?

对于较新版本的Android,您可以简单地执行此操作:

getActionBar().getHeight()
Run Code Online (Sandbox Code Playgroud)

  • 即使isShowing为true(可能在动画期间),getHeight()也可以返回0.在某些情况下,您可能需要使用attributes方法. (3认同)