Узнать значение цвета программно, когда он'ы ссылка (тема)

Рассматривайте это:

styles.xml

<style name="BlueTheme" parent="@android:style/Theme.Black.NoTitleBar">
    <item name="theme_color">@color/theme_color_blue</item>
</style>

attrs.xml

<attr name="theme_color" format="reference" />

color.xml

<color name="theme_color_blue">#ff0071d3</color>

Поэтому тема цвет ссылки по теме. Как я могу получить theme_color (ссылка) программно? Обычно я бы использовать getResources().хеттолог()` но не в этом дело, потому что он'ы, на которые ссылается!

Решение

Это должно сделать работу:

TypedValue typedValue = new TypedValue();
Theme theme = context.getTheme();
theme.resolveAttribute(R.attr.theme_color, typedValue, true);
@ColorInt int color = typedValue.data;

Также убедитесь, чтобы применить тему к вашей деятельности, прежде чем называть настоящим Кодексом. Либо использовать:

android:theme="@style/Theme.BlueTheme"

в манифесте или позвоните по телефону (прежде чем позвонить setContentView(инт)`):

setTheme(R.style.Theme_BlueTheme)

в методе onCreate()`.

Я'протестировали его с вашими ценностями и он работал отлично.

Комментарии (16)

Этот работал для меня:

int[] attrs = {R.attr.my_attribute};
TypedArray ta = context.obtainStyledAttributes(attrs);
int color = ta.getResourceId(0, android.R.color.black);
ta.recycle();

если вы хотите получить hexstring из него:

Integer.toHexString(color)
Комментарии (2)

Добавить к принято отвечать, если вы're через Котлин.

fun Context.getColorFromAttr(
    @AttrRes attrColor: Int,
    typedValue: TypedValue = TypedValue(),
    resolveRefs: Boolean = true
): Int {
    theme.resolveAttribute(attrColor, typedValue, resolveRefs)
    return typedValue.data
}

и тогда в вашей деятельности вы можете сделать

поле TextView.setTextColor(getColorFromAttr(Р. привлекательными.цвет))

Комментарии (3)

Если вы хотите сделать несколько цветов, вы можете использовать:

int[] attrs = {R.attr.customAttr, android.R.attr.textColorSecondary, 
        android.R.attr.textColorPrimaryInverse};
Resources.Theme theme = context.getTheme();
TypedArray ta = theme.obtainStyledAttributes(attrs);

int[] colors = new int[attrs.length];
for (int i = 0; i < attrs.length; i++) {
    colors[i] = ta.getColor(i, 0);
}

ta.recycle();
Комментарии (0)

Здесь's в сжатой служебный метод Java, который принимает несколько атрибутов и возвращает массив целых чисел цвета. :)

/**
 * @param context    Pass the activity context, not the application context
 * @param attrFields The attribute references to be resolved
 * @return int array of color values
 */
@ColorInt
static int[] getColorsFromAttrs(Context context, @AttrRes int... attrFields) {
    int length = attrFields.length;
    Resources.Theme theme = context.getTheme();
    TypedValue typedValue = new TypedValue();

    @ColorInt int[] colorValues = new int[length];

    for (int i = 0; i < length; ++i) {
        @AttrRes int attr = attrFields[i];
        theme.resolveAttribute(attr, typedValue, true);
        colorValues[i] = typedValue.data;
    }

    return colorValues;
}
Комментарии (0)

Для тех, кто ищет ссылку на катры, вы должны использовать false в resolveRefs

тему.resolveAttribute(Р. привлекательными.some_drawable, typedValue, ложь);`

Комментарии (0)