Подтвердить что ты не робот

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

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

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

Ответ 1

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

Чтобы получить значение атрибута 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

Ответ 2

Используя

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

Ответ 3

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

Если вам просто нужно получить измерение, например заполнение, 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 );

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

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

Ответ 4

это мой код.

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