How to get accent color programmatically?
44,406
Solution 1
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;
}
Solution 2
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;
}
Solution 3
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;
}
Solution 4
For those of you using Kotlin
@ColorInt
fun Context.themeColor(@AttrRes attrRes: Int): Int = TypedValue()
.apply { theme.resolveAttribute (attrRes, this, true) }
.data
Solution 5
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;
}
Author by
Jakob
Updated on January 18, 2022Comments
-
Jakob over 2 years
How would one fetch the accent color set in styles, like below, programmatically?
<item name="android:colorAccent">@color/material_green_500</item>