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


当前回答

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

其他回答

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

@dimen/abs__action_bar_default_height

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

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

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

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

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

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