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


当前回答

我这样做是为了自己,这个帮手方法应该对其他人有用:

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

其他回答

为了获得动作栏的实际高度,你必须在运行时解析actionBarSize属性。

TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
int actionBarHeight = getResources().getDimensionPixelSize(tv.resourceId);

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

在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来看)…

我这样做是为了自己,这个帮手方法应该对其他人有用:

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

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

@dimen/abc_action_bar_default_height

文档