我需要知道ActionBar的确切像素大小,以便应用正确的背景图片。
要在XML中检索ActionBar的高度,只需使用:
?android:attr/actionBarSize
如果您使用ActionBarSherlock或AppCompat,请使用此代码
?attr/actionBarSize
如果您需要在运行时获取此值,请使用以下方法
final TypedArray styledAttributes = getContext().getTheme().obtainStyledAttributes(
new int[] { android.R.attr.actionBarSize });
mActionBarSize = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();
如果您需要了解这个属性是在哪里定义的:
从反编译的Android 3.2 framework-res.apk
源代码中,res/values/styles.xml
包含:
<style name="Theme.Holo">
<!-- ... -->
<item name="actionBarSize">56.0dip</item>
<!-- ... -->
</style>
从AOSP来看,3.0和3.1似乎是相同的...
要获取操作栏(Actionbar)的实际高度,您需要在运行时解析属性actionBarSize
。
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId);
其中一个蜂窝样本涉及到?android:attr/actionBarSize
?attr/actionBarSize
这个属性(注意没有android命名空间),在所有API级别上都可以使用。 - Jake Wharton我需要在一个兼容pre-ICS版本的应用程序中正确复制这些高度,并深入挖掘框架核心源代码。以上两个答案都有点正确。
基本上,这归结于使用限定符。高度由维度 "action_bar_default_height" 定义。
它被定义为默认的48dip。但是对于-land,它是40dip,对于sw600dp,它是56dip。
使用新的v7支持库(21.0.0),R.dimen
中的名称已更改为@dimen/abc_action_bar_default_height_material。
从旧版本的支持库升级后,您应该使用该值作为操作栏的高度。
?attr/actionBarSize
更好。 - karllindmark如果您正在使用ActionBarSherlock,请使用以下代码获取高度:
@dimen/abs__action_bar_default_height
abs__
前缀开头的资源。 - Jake WhartonKotlin中的被接受的答案:
val Context.actionBarSize
get() = theme.obtainStyledAttributes(intArrayOf(android.R.attr.actionBarSize))
.let { attrs -> attrs.getDimension(0, 0F).toInt().also { attrs.recycle() } }
用法:
val size = actionBarSize // Inside Activity
val size = requireContext().actionBarSize // Inside Fragment
val size = anyView.context.actionBarSize // Inside RecyclerView ViewHolder
@dimen/abc_action_bar_default_height
(ActionBarComapt),并且它在mdpi设备上运行良好。但是,在三星Galaxy SIII上尝试获取此值会返回错误的值。这是因为在横向模式下,“values-xlarge”(不知何故)比“values-land”更受欢迎。引用属性就像魔法一样奏效。 - Alex Semeniukandroid.R.attr.actionBarSize
在3.0以下的设备上会解析为0大小。因此,在使用ActionBarCompat
时,应使用android.support.v7.appcompat.R.attr.actionBarSize
。 - Drew