Jakob Harteg
Jakob Harteg

Reputation: 9497

How to get accent color programmatically?

How would one fetch the accent color set in styles, like below, programmatically?

    <item name="android:colorAccent">@color/material_green_500</item>

Upvotes: 108

Views: 53153

Answers (10)

Noor Hossain
Noor Hossain

Reputation: 1831

Some Modificatio of rciovati's Answer: (Ofcourse for main three colors) :

public static int getThemeColor(Context mContext, String which) {

        TypedValue typedValue = new TypedValue();
        int color = -1;

        TypedArray a = null;
        try {

            if (which != null) {
                switch (which) {
                    case "primary":
                        try {
                            a = mContext.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorPrimary});
                        } catch (Resources.NotFoundException e) {
                            e.printStackTrace();
                        }
                        break;
                    case "accent":
                        try {
                            a = mContext.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorAccent});
                        } catch (Resources.NotFoundException e) {
                            e.printStackTrace();
                        }
                        break;

                    default:
                        try {
                            a = mContext.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorPrimaryDark});
                        } catch (Resources.NotFoundException e) {
                            e.printStackTrace();
                        }
                        break;
                }
            }else {
                try {
                    a = mContext.obtainStyledAttributes(typedValue.data, new int[]{R.attr.colorPrimaryDark});
                } catch (Resources.NotFoundException e) {
                    e.printStackTrace();
                }
            }

            if(a!=null) {
                color = a.getColor(0, 0);
                a.recycle();
            }
        } catch (Resources.NotFoundException e) {
            e.printStackTrace();
        }

        return color;

    }

Upvotes: 0

copolii
copolii

Reputation: 14506

This also worked for me:

public static int getThemeAccentColor (final Context context) {
    final TypedValue value = new TypedValue ();
    context.getTheme ().resolveAttribute (R.attr.colorAccent, value, true);
    return value.data;
}

Upvotes: 54

Andoctorey
Andoctorey

Reputation: 778

When you use Theme.Material3 you have to combine both solutions mentioned here because one works for R.attr and another one for android.R.attr.

@ColorInt
fun Context.getThemeColor(@AttrRes attrRes: Int): Int {
    val materialColor = MaterialColors.getColor(this, attrRes, Color.BLUE)
    if (materialColor< 0) return materialColor

    val resolvedAttr = TypedValue()
    theme.resolveAttribute(attrRes, resolvedAttr, true)
    val colorRes = resolvedAttr.run { if (resourceId != 0) resourceId else data }
    return ContextCompat.getColor(this, colorRes)
}

Upvotes: 0

Kevin
Kevin

Reputation: 1443

For those of you using Kotlin

@ColorInt
fun Context.themeColor(@AttrRes attrRes: Int): Int = TypedValue()
    .apply { theme.resolveAttribute (attrRes, this, true) }
    .data

Upvotes: 24

Ismail Iqbal
Ismail Iqbal

Reputation: 2580

The MaterialColors could be used in this case if you want it to be single line

            MaterialColors.getColor(context, R.attr.colorAccent,context.getResources().getColor(R.color.fall_back_color));

The first argument is the context the second argument is the attribute you need to get and the third argument is the fallback color incase the attribute is missing or something goes wrong while getting the attribute color

Upvotes: 5

android developer
android developer

Reputation: 115952

Kotlin solution:

    context.obtainStyledAttributes(TypedValue().data, intArrayOf(R.attr.colorAccent)).let {
        Log.d("AppLog", "color:${it.getColor(0, 0).toHexString()}")
        it.recycle()
    }

Upvotes: 2

Esdras Lopez
Esdras Lopez

Reputation: 775

Here's my take on this:

public static String getThemeColorInHex(@NonNull Context context, @NonNull String colorName, @AttrRes int attribute) {
    TypedValue outValue = new TypedValue();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        context.getTheme().resolveAttribute(attribute, outValue, true);
    } else {
        // get color defined for AppCompat
        int appCompatAttribute = context.getResources().getIdentifier(colorName, "attr", context.getPackageName());
        context.getTheme().resolveAttribute(appCompatAttribute, outValue, true);
    }
    return String.format("#%06X", (0xFFFFFF & outValue.data));
}

Usage:

    String windowBackgroundHex = getThemeColorInHex(this, "windowBackground", android.R.attr.windowBackground);
    String primaryColorHex = getThemeColorInHex(this, "colorPrimary", R.attr.colorPrimary);

Upvotes: 9

XYz Amos
XYz Amos

Reputation: 1503

private static int getThemeAccentColor(Context context) {
    int colorAttr;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        colorAttr = android.R.attr.colorAccent;
    } else {
        //Get colorAccent defined for AppCompat
        colorAttr = context.getResources().getIdentifier("colorAccent", "attr", context.getPackageName());
    }
    TypedValue outValue = new TypedValue();
    context.getTheme().resolveAttribute(colorAttr, outValue, true);
    return outValue.data;
}

Upvotes: 33

Sotti
Sotti

Reputation: 14399

I have an static method on a utils class to get the colors from the current theme. Most of times is colorPrimary, colorPrimaryDark and accentColor, but you can get a lot more.

@ColorInt
public static int getThemeColor
(
        @NonNull final Context context,
        @AttrRes final int attributeColor
)
{
    final TypedValue value = new TypedValue();
    context.getTheme ().resolveAttribute (attributeColor, value, true);
    return value.data;
}

Upvotes: 12

rciovati
rciovati

Reputation: 28063

You can fetch it from the current theme in this way:

private int fetchAccentColor() {
    TypedValue typedValue = new TypedValue();

    TypedArray a = mContext.obtainStyledAttributes(typedValue.data, new int[] { R.attr.colorAccent });
    int color = a.getColor(0, 0);

    a.recycle();

    return color;
}

Upvotes: 149

Related Questions