Android: как получить значение атрибута в коде?

Я хотел бы получить значение int textApperanceLarge в коде. Я считаю, что приведенный ниже код движется в правильном направлении, но не могу понять, как извлечь значение int из TypedValue.

TypedValue typedValue = new TypedValue(); 
((Activity)context).getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);

4 ответа

Решение

Ваш код получает только идентификатор ресурса стиля, на который указывает атрибут textAppearanceLarge, а именно TextAppearance.Large, как указывает Рено.

Чтобы получить значение атрибута textSize из стиля, просто добавьте этот код:

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();

Теперь textSize будет размером текста в пикселях стиля, на который указывает textApperanceLarge, или -1, если он не был установлен. Предполагается, что для начала typedValue.type имел тип TYPE_REFERENCE, поэтому сначала следует проверить это.

Номер 16973890 проистекает из того факта, что это идентификатор ресурса TextAppearance.Large

С помощью

  TypedValue typedValue = new TypedValue(); 
  ((Activity)context).getTheme().resolveAttribute(android.R.attr.textAppearanceLarge, typedValue, true);

Для строки:

typedValue.string
typedValue.coerceToString()

Для других данных:

typedValue.resourceId
typedValue.data  // (int) based on the type

В вашем случае он возвращает TYPE_REFERENCE,

Я знаю, что это должно указывать на TextAppearance.Large

Который:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
    <item name="android:textStyle">normal</item>
    <item name="android:textColor">?textColorPrimary</item>
</style>

Благодарим Мартина за решение этой проблемы:

int[] attribute = new int[] { android.R.attr.textSize };
TypedArray array = context.obtainStyledAttributes(typedValue.resourceId, attribute);
int textSize = array.getDimensionPixelSize(0, -1);

Или в котлин

fun Context.dimensionFromAttribute(attribute: Int): Int {
    val attributes = obtainStyledAttributes(intArrayOf(attribute))
    val dimension = attributes.getDimensionPixelSize(0, 0)
    attributes.recycle()
    return dimension
}

Кажется, это инквизиция ответа @user3121370. Они сгорели.:O

Если вам просто нужно получить измерение, например padding, minHeight (мой случай: android.R.attr.listPreferredItemPaddingStart). Ты можешь сделать:

TypedValue typedValue = new TypedValue(); 
((Activity)context).getTheme().resolveAttribute(android.R.attr.listPreferredItemPaddingStart, typedValue, true);

Так же, как вопрос, а затем:

final DisplayMetrics metrics = new android.util.DisplayMetrics();
WindowManager wm = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
wm.getDefaultDisplay().getMetrics(metrics);
int myPaddingStart = typedValue.getDimension( metrics );

Так же, как удаленный ответ. Это позволит вам пропустить обработку размеров пикселей устройства, потому что он использует метрику устройства по умолчанию. Возврат будет float, и вы должны привести к int.

Будьте осторожны с типом, который вы пытаетесь получить, например, resourceId.

Это мой код

public static int getAttributeSize(int themeId,int attrId, int attrNameId)
{
    TypedValue typedValue = new TypedValue();
    Context ctx = new ContextThemeWrapper(getBaseContext(), themeId);

    ctx.getTheme().resolveAttribute(attrId, typedValue, true);

    int[] attributes = new int[] {attrNameId};
    int index = 0;
    TypedArray array = ctx.obtainStyledAttributes(typedValue.data, attributes);
    int res = array.getDimensionPixelSize(index, 0);
    array.recycle();
    return res;
} 

// getAttributeSize(theme, android.R.attr.textAppearanceLarge, android.R.attr.textSize)   ==>  return android:textSize
Другие вопросы по тегам