如何获取作为属性引用的维度值?

How to get a dimension value that is a reference to an attribute?

我的维度定义中有这两项:

<dimen name="toolbar_search_extended_height">158dp</dimen>
<dimen name="toolbar_search_normal_height">?attr/actionBarSize</dimen>

现在我想在运行时获取以像素为单位的实际值:

height = getResources().getDimensionPixelOffset(R.dimen.toolbar_search_extended_height);
height = getResources().getDimensionPixelOffset(R.dimen.toolbar_search_normal_height);

第一次调用给出了设备上以像素为单位的 158dp。
第二次调用产生 NotFoundException:

android.content.res.Resources$NotFoundException: Resource ID #0x7f080032 type #0x2 is not valid

类型 0x2 是:TypedValue#TYPE_ATTRIBUTE:

/** The <var>data</var> field holds an attribute resource
 *  identifier (referencing an attribute in the current theme
 *  style, not a resource entry). */
public static final int TYPE_ATTRIBUTE = 0x02;

取消引用 dimen 可以是实际值或对样式属性的引用的值的首选方法是什么?

这是我实现的,但感觉很麻烦和 hacky:

private int getDimension(@DimenRes int resId) {
    final TypedValue value = new TypedValue();
    getResources().getValue(resId, value, true);

    if (value.type == TypedValue.TYPE_ATTRIBUTE) {
        final TypedArray attributes = getTheme().obtainStyledAttributes(new int[]{value.data});
        int dimension = attributes.getDimensionPixelOffset(0, 0);
        attributes.recycle();
        return dimension;
    } else {
        return getResources().getDimensionPixelOffset(resId);
    }
}

我希望框架能直接取消引用我的 ?attr/ 维度。