如何以编程方式获取如下样式中的强调色?
<item name="android:colorAccent">@color/material_green_500</item>
Answers:
您可以通过以下方式从当前主题中获取它:
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;
}
这也为我工作:
public static int getThemeAccentColor (final Context context) {
final TypedValue value = new TypedValue ();
context.getTheme ().resolveAttribute (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().resolveAttribute(colorAttr, outValue, true);
return outValue.data;
}
我在utils类上有一个静态方法来从当前主题获取颜色。大多数时候是colorPrimary,colorPrimaryDark和accentColor,但是您可以获得更多。
@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;
}
这是我的看法:
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));
}
用法:
String windowBackgroundHex = getThemeColorInHex(this, "windowBackground", android.R.attr.windowBackground);
String primaryColorHex = getThemeColorInHex(this, "colorPrimary", R.attr.colorPrimary);
String.format()
有助于解释如何将负整数值转换为十六进制颜色字符串。
Kotlin解决方案:
context.obtainStyledAttributes(TypedValue().data, intArrayOf(R.attr.colorAccent)).let {
Log.d("AppLog", "color:${it.getColor(0, 0).toHexString()}")
it.recycle()
}