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

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

Рассмотрим это:

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 (reference) программно? Обычно я использовал бы getResources().getColor(), но не в этом случае, потому что он ссылался!

4b9b3361

Ответ 1

Это должно выполнить задание:

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(int)):

setTheme(R.style.Theme_BlueTheme)

в onCreate().

Я тестировал его с вашими значениями, и он отлично работал.

Ответ 2

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

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

если вы хотите получить из него шестую строку:

Integer.toHexString(color)

Ответ 3

Чтобы добавить к принятому ответу, если вы используете kotlin.

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

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

textView.setTextColor(getColorFromAttr(R.attr.color))

Ответ 4

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

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

Ответ 5

Здесь краткий служебный метод 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;
}