Comment obtenir les couleurs d’accent par programmation?

Comment récupérer la couleur d’accent définie dans les styles, comme ci-dessous, par programmation?

@color/material_green_500 

Vous pouvez le récupérer du thème actuel de cette manière:

 private int fetchAccentColor() { TypedValue typedValue = new TypedValue(); TypedArray a = mContext.obtainStyledAtsortingbutes(typedValue.data, new int[] { R.attr.colorAccent }); int color = a.getColor(0, 0); a.recycle(); return color; } 

Cela a fonctionné pour moi aussi:

 public static int getThemeAccentColor (final Context context) { final TypedValue value = new TypedValue (); context.getTheme ().resolveAtsortingbute (R.attr.colorAccent, value, true); return value.data; } 
 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().resolveAtsortingbute(colorAttr, outValue, true); return outValue.data; } 

J’ai une méthode statique sur une classe d’utils pour obtenir les couleurs du thème actuel. La plupart du temps, il s’agit de colorPrimary, colorPrimaryDark et accentColor, mais vous pouvez en obtenir beaucoup plus.

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

Voici ma prise sur ceci:

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

Usage:

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