Skip to content

Instantly share code, notes, and snippets.

@muiz6
Last active August 15, 2020 13:30
Show Gist options
  • Save muiz6/5e0f11a758c3824ff633f2605e426333 to your computer and use it in GitHub Desktop.
Save muiz6/5e0f11a758c3824ff633f2605e426333 to your computer and use it in GitHub Desktop.
How to get color from a theme attribute with java in android.
package com.muiz6.example;
import android.content.Context;
import android.content.res.Resources;
import android.util.TypedValue;
import androidx.annotation.AttrRes;
import androidx.annotation.ColorInt;
import androidx.annotation.ColorRes;
import androidx.annotation.NonNull;
import androidx.core.content.ContextCompat;
public abstract class ThemeUtil {
@ColorInt
public static int getColor(@NonNull Context context, @AttrRes int resId) {
final Resources.Theme theme = context.getTheme();
final TypedValue typedValue = new TypedValue();
theme.resolveAttribute(resId, typedValue, true);
@ColorRes final int colorId = typedValue.resourceId;
return ContextCompat.getColor(context, colorId);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment