我需要知道 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>
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。
获取高度
@dimen/abs__action_bar_default_height
Android 设计指南,ActionBar 应该是 至少 48dp 高。
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
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;
}
使用公式 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;
}
<item name="actionBarSize">@dimen/abc_action_bar_default_height_material</item>
// values.xml
<dimen name="abc_action_bar_default_height_material">56dp</dimen>
//values-land.xml
<dimen name="abc_action_bar_default_height_material">48dp</dimen>
//values-sw600dp-v13.xml
<dimen name="abc_action_bar_default_height_material">64dp</dimen>