我尝试了像这样的东西,但是我卡住了:
TypedValue typedValue = new TypedValue();
if (this.parentActivity.getTheme().resolveAttribute(android.R.attr.windowBackground, typedValue, true))
{
// how to get color?
}
我尝试了像这样的东西,但是我卡住了:
TypedValue typedValue = new TypedValue();
if (this.parentActivity.getTheme().resolveAttribute(android.R.attr.windowBackground, typedValue, true))
{
// how to get color?
}
您可以通过以下方式从当前主题中获取背景颜色(或Drawable):
TypedValue a = new TypedValue();
getTheme().resolveAttribute(android.R.attr.windowBackground, a, true);
if (a.isColorType()) {
// windowBackground is a color
int color = a.data;
} else {
// windowBackground is not a color, probably a drawable
Drawable d = activity.getResources().getDrawable(a.resourceId);
}
isColorType在API 29级中引入。 在此之前,您可以改为使用以下内容:
if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT)
<item name="someColor>
),并在我自己的attrs.xml
中声明;但是背景颜色是限定的(<item name="android:background">
),它在Android系统中某处声明,而不是在我的attrs.xml
中像其他属性一样。因此,背景颜色不是我的应用程序的属性,而是任何/每个 Android应用程序的属性。这就是区别的原因。 - jpaughisColorType
。感谢你的帮助! - jpaugh您可以使用以下方式获取主题的资源:
TypedArray a = getTheme().obtainStyledAttributes(R.style.ThemeName, new int[] {R.attr.attribute_name});
int attributeResourceId = a.getResourceId(0, 0);
int aaa = this.parentActivity.getResources().getColor(attributeResourceId); 但是它没有起作用。我得到了异常。
- Bartłomiej Muchaandroid:color
属性的<item>标签。 - Swayam对于你的问题,最简单的方法是:
TypedValue typedValue = new TypedValue();
if (this.parentActivity.getTheme().resolveAttribute(android.R.attr.windowBackground, typedValue, true))
{
// how to get color?
int colorWindowBackground = typedValue.data;// **just add this line to your code!!**
}
?android:attr/colorBackground
对应于styles.xml
中的<item name="android:colorBackground">@color/yourColorHere</item>
。 - Rock Lee