How would one fetch the accent color set in styles, like below, programmatically?
- @color/material_green_500<
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);