How to get the dimension value, which is an attribute reference?

I have these two elements in my size definitions:

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

Now I want to get the actual value in pixels at runtime:

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

The first call gives any value of 158dp in pixels on the device.
The second call gives a NotFoundException:

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

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

What is the preferred method for dereferencing values dimen, which can be either actual values ​​or references to stylized attributes?

+4
source share
1 answer

This is what I implemented, but it looks bulky and hacked:

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/.

+4

All Articles