为您希望跨主题具有不同的资源创建一个属性。
<attr name="someTextColor" format="color"/>
现在在您的主题中,定义属性
<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);