Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: how to get value of an attribute in code?

Tags:

android

I would like to retrieve the int value of textApperanceLarge in code. I believe that the below code is going in the right direction, but can't figure out how to extract the int value from the TypedValue.

TypedValue typedValue = new TypedValue(); 
((Activity)context).getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);
like image 820
ab11 Avatar asked Oct 25 '11 22:10

ab11


2 Answers

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

like image 188
Martin Nordholts Avatar answered Oct 01 '22 08:10

Martin Nordholts


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);
like image 41
Reno Avatar answered Oct 01 '22 07:10

Reno