Android: how to get value of an attribute in code?
Solution 1:
Your code only gets the resource ID of the style that the textAppearanceLarge attribute points to, namely TextAppearance.Large as Reno points out.
To get the textSize attribute value from the style, just add this code:
int[] textSizeAttr = new int[] { android.R.attr.textSize };
int indexOfAttrTextSize = 0;
TypedArray a = context.obtainStyledAttributes(typedValue.data, textSizeAttr);
int textSize = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();
Now textSize will be the text size in pixels of the style that textApperanceLarge points to, or -1 if it wasn't set. This is assuming typedValue.type was of type TYPE_REFERENCE to begin with, so you should check that first.
The number 16973890 comes from the fact that it is the resource ID of TextAppearance.Large
Solution 2:
Using
TypedValue typedValue = new TypedValue();
((Activity)context).getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);
For the string :
typedValue.string
typedValue.coerceToString()
For other data :
typedValue.resourceId
typedValue.data // (int) based on the type
In your case what it returns is of the TYPE_REFERENCE
.
I know it should point to TextAppearance.Large
Which is :
<style name="TextAppearance.Large">
<item name="android:textSize">22sp</item>
<item name="android:textStyle">normal</item>
<item name="android:textColor">?textColorPrimary</item>
</style>
Credit goes to Martin for resolving this :
int[] attribute = new int[] { android.R.attr.textSize };
TypedArray array = context.obtainStyledAttributes(typedValue.resourceId, attribute);
int textSize = array.getDimensionPixelSize(0, -1);
Solution 3:
Or in kotlin:
fun Context.dimensionFromAttribute(attribute: Int): Int {
val attributes = obtainStyledAttributes(intArrayOf(attribute))
val dimension = attributes.getDimensionPixelSize(0, 0)
attributes.recycle()
return dimension
}
Solution 4:
It seems to be an inquisition on the @user3121370's answer. They burned down. :O
If you just need the get a dimension, like a padding, minHeight (my case was: android.R.attr.listPreferredItemPaddingStart). You can do:
TypedValue typedValue = new TypedValue();
((Activity)context).getTheme().resolveAttribute(android.R.attr.listPreferredItemPaddingStart, typedValue, true);
Just like the question did, and then:
final DisplayMetrics metrics = new android.util.DisplayMetrics();
WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
int myPaddingStart = typedValue.getDimension( metrics );
Just like the removed answer. This will allow you to skip handling device pixel sizes, because it uses the default device metric. The return will be float, and you should cast to int.
Becareful to the type you are trying to get, like resourceId.