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


当前回答

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

其他回答

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

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

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

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

如果你在使用ActionBarSherlock,你可以用

@dimen/abs__action_bar_default_height

在我的Galaxy S4上有> 441dpi > 1080 x 1920 > 使用getResources()获取动作栏高度。我得到144像素。

使用公式px = dp x (dpi/160),我使用的是441dpi,而我的设备位于 在类别480dpi。这样就证实了这个结果。