이 점을 고려하십시오.
*marget.xml
<style name="BlueTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="theme_color">@color/theme_color_blue</item>
</style>
attrs.xml
<attr name="theme_color" format="reference" />
color.xml
<color name="theme_color_blue">#ff0071d3</color>
따라서 테마 색상은 테마에 의해 참조됩니다. tema_color(참조)를 프로그래밍 방식으로 가져오려면 어떻게 해야 합니까? 일반적으로 'getResources().getColor()'를 사용하지만, 이 경우에는 '가 참조되므로 사용하지 않습니다!
이렇게 하면 됩니다.
TypedValue typedValue = new TypedValue();
Theme theme = context.getTheme();
theme.resolveAttribute(R.attr.theme_color, typedValue, true);
@ColorInt int color = typedValue.data;
또한 이 코드를 호출하기 전에 테마를 활동에 적용해야 합니다. 다음 중 하나를 사용합니다.
android:theme="@style/Theme.BlueTheme"
매니페스트 또는 호출에서 ('setContentView(int)'를 호출하기 전에):
setTheme(R.style.Theme_BlueTheme)
"on Create()"에서 파생된.
당신의 가치로 테스트해봤는데 완벽하게 작동했어요.
이건 제게 효과가 있었어요.
int[] attrs = {R.attr.my_attribute};
TypedArray ta = context.obtainStyledAttributes(attrs);
int color = ta.getResourceId(0, android.R.color.black);
ta.recycle();
16진수 문자열을 추출하고 싶다면:
Integer.toHexString(color)
fun Context.getColorFromAttr(
@AttrRes attrColor: Int,
typedValue: TypedValue = TypedValue(),
resolveRefs: Boolean = true
): Int {
theme.resolveAttribute(attrColor, typedValue, resolveRefs)
return typedValue.data
}
자신의 활동 할 수 있습니다 다음
'테스트비에웨인스테스트콜러 (제콜로프로마테르 (R. 아트리코로)'
여러 색상을 원하는 경우 다음을 사용할 수 있습니다.
int[] attrs = {R.attr.customAttr, android.R.attr.textColorSecondary,
android.R.attr.textColorPrimaryInverse};
Resources.Theme theme = context.getTheme();
TypedArray ta = theme.obtainStyledAttributes(attrs);
int[] colors = new int[attrs.length];
for (int i = 0; i < attrs.length; i++) {
colors[i] = ta.getColor(i, 0);
}
ta.recycle();
/**
* @param context Pass the activity context, not the application context
* @param attrFields The attribute references to be resolved
* @return int array of color values
*/
@ColorInt
static int[] getColorsFromAttrs(Context context, @AttrRes int... attrFields) {
int length = attrFields.length;
Resources.Theme theme = context.getTheme();
TypedValue typedValue = new TypedValue();
@ColorInt int[] colorValues = new int[length];
for (int i = 0; i < length; ++i) {
@AttrRes int attr = attrFields[i];
theme.resolveAttribute(attr, typedValue, true);
colorValues[i] = typedValue.data;
}
return colorValues;
}