How to get accent color programmatically?

How to choose the accent color set in the styles, for example below, programmatically?

<item name="android:colorAccent">@color/material_green_500</item> 
+80
android android-xml android-styles
Dec 22 '14 at 22:08
source share
4 answers

You can extract it from the current topic as follows:

 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; } 
+120
Dec 22 '14 at 22:14
source share

This worked for me too:

 public static int getThemeAccentColor (final Context context) { final TypedValue value = new TypedValue (); context.getTheme ().resolveAttribute (R.attr.colorAccent, value, true); return value.data; } 
+38
Feb 28 '15 at 2:37
source share
 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; } 
+23
Mar 24 '16 at 3:27
source share

I have a static utils class method to get colors from the current theme. Most often it 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; } 
+11
Feb 06 '16 at 22:16
source share



All Articles