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


当前回答

在新的v7支持库(21.0.0)中,R.dimen中的名称已更改为@dimen/ abc_action_bar_default_highight_material。

当从以前版本的支持库升级时,您应该使用该值作为动作栏的高度

其他回答

课程摘要通常是一个很好的开始。我认为getHeight()方法就足够了。

编辑:

如果你需要宽度,它应该是屏幕的宽度(对吧?),可以像这样收集。

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

@dimen/abc_action_bar_default_height

文档

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;
}

要在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

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