我需要知道 ActionBar 的确切大小(以像素为单位),以便应用正确的背景图像。
14 回答
要在 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();
如果您需要了解这是在哪里定义的:
- 属性名称本身在平台的/res/values/attrs.xml中定义
- 平台的themes.xml选择此属性并为其分配一个值。
- 步骤2中分配的值取决于不同的设备大小,在平台的各种dimens.xml文件中定义,即。核心/res/res/values-sw600dp/dimens.xml
从 Android 3.2 的反编译源中framework-res.apk
,res/values/styles.xml
包含:
<style name="Theme.Holo">
<!-- ... -->
<item name="actionBarSize">56.0dip</item>
<!-- ... -->
</style>
3.0 和 3.1 似乎是一样的(至少来自 AOSP)...
要获取 Actionbar 的实际高度,您必须actionBarSize
在运行时解析该属性。
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId);
蜂窝样品之一是指?android:attr/actionBarSize
我需要在 ICS 之前的兼容性应用程序中正确复制这些高度,并深入研究框架核心源代码。上面的两个答案都是正确的。
它基本上归结为使用限定符。高度由维度“action_bar_default_height”定义
默认定义为 48dip。但是对于-land,它是40dip,对于sw600dp,它是56dip。
使用新的v7 支持库(21.0.0) 中的名称R.dimen
已更改为@dimen/abc_action_bar_default_height_ material。
因此,从以前版本的支持库升级时,您应该使用该值作为操作栏的高度
如果您使用的是 ActionBarSherlock,您可以使用
@dimen/abs__action_bar_default_height
@AZ13 的回答很好,但根据Android 设计指南,ActionBar至少应为48dp 高。
public int getActionBarHeight() {
int actionBarHeight = 0;
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 {
actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,
getResources().getDisplayMetrics());
}
return actionBarHeight;
}
Kotlin 中接受的答案:
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
在我的 Galaxy S4 上具有 > 441dpi > 1080 x 1920 > 使用 getResources().getDimensionPixelSize 获取操作栏高度我得到 144 像素。
使用公式 px = dp x (dpi/160),我使用的是 441dpi,而我的设备属于 480dpi
类别。所以把这证实了结果。
我为自己这样做了,这个辅助方法应该对某人派上用场:
private static final int[] RES_IDS_ACTION_BAR_SIZE = {R.attr.actionBarSize};
/**
* Calculates the Action Bar height in pixels.
*/
public static int calculateActionBarSize(Context context) {
if (context == null) {
return 0;
}
Resources.Theme curTheme = context.getTheme();
if (curTheme == null) {
return 0;
}
TypedArray att = curTheme.obtainStyledAttributes(RES_IDS_ACTION_BAR_SIZE);
if (att == null) {
return 0;
}
float size = att.getDimension(0, 0);
att.recycle();
return (int) size;
}