我需要知道动作栏的像素大小,以便应用正确的背景图像。


当前回答

要在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步中分配的值取决于不同的设备大小,这些设备大小在平台中的各种dimensions .xml文件中定义,例如。核心/ res / res / values-sw600dp / dimens.xml

其他回答

我需要在一个pre-ICS兼容应用程序中正确复制这些高度,并深入研究框架核心源代码。以上两个答案都是正确的。

它基本上可以归结为使用限定词。高度由维度"action_bar_default_height"定义

默认定义为48dip。但是对于-land是40dip,对于sw600dp是56dip。

要在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步中分配的值取决于不同的设备大小,这些设备大小在平台中的各种dimensions .xml文件中定义,例如。核心/ res / res / values-sw600dp / dimens.xml

如果你正在使用最近的v7 appcompat支持包中的兼容ActionBar,你可以使用

@dimen/abc_action_bar_default_height

文档

蜂窝样本之一是指?android:attr/actionBarSize

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