創建你想擁有整個主題不同的資源生成的attr。
<attr name="someTextColor" format="color"/>
在你的主題
現在,定義ATTRS
<style name="WhiteTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="someTextColor">@android:color/black</item>
</style>
<style name="DarkTheme" parent="Theme.AppCompat">
<item name="someTextColor">@android:color/white</item>
</style>
現在你可以使用它們。
<style name="BodyText" parent="TextAppearance.AppCompat.Body1">
<item name="android:textSize">14sp</item>
<item name="android:textColor">?attr/someTextColor</item>
</style>
您也可以從代碼
得到ATTR
/**
* Returns color for attr from the {@link Theme}
*
* @param theme {@link Theme} to get int from
* @param attr Attribute of the int
* @return dimension for attr from the {@link Theme}
*/
@ColorInt
public static int getColor(@NonNull final Theme theme, @AttrRes final int attr) {
final TypedArray array = theme.obtainStyledAttributes(new int[]{attr});
try {
return array.getColor(0, Color.TRANSPARENT);
} finally {
array.recycle();
}
}
或者作爲ColorStateList
/**
* Returns {@link ColorStateList} for attr from the {@link Theme}
*
* @param theme {@link Theme} to get int from
* @param attr Attribute of the int
* @return dimension for attr from the {@link Theme}
*/
@Nullable
public static ColorStateList getColorStateList(@NonNull final Theme theme,
@AttrRes final int attr) {
final TypedArray array = theme.obtainStyledAttributes(new int[]{attr});
try {
return array.getColorStateList(0);
} finally {
array.recycle();
}
}
然後
final int someTextColor = getColor(getTheme(), R.attr.someTextColor);
// or
final ColorStateList someTextColor = getColorStateList(getTheme(), R.attr.someTextColor);
非常感謝!這正是我正在尋找的。 – manabreak