Issue
I've got these two items in my dimension definitions:
<dimen name="toolbar_search_extended_height">158dp</dimen>
<dimen name="toolbar_search_normal_height">?attr/actionBarSize</dimen>
Now I'd like 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 whatever 158dp is in pixels on the device.
The second call yields a NotFoundException
:
android.content.res.Resources$NotFoundException: Resource ID #0x7f080032 type #0x2 is not valid
Type 0x2
is: 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 to dereference dimen
values that can be either actual values or references to styled attributes?
Solution
This is what I implemented but it feels cumbersome and 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);
}
}
I was hoping that the framework would dereference my ?attr/
dimension directly.
Answered By - Benoit Duffez
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.