如何以编程方式从当前主题获取背景颜色

Bar*_*cha 31 android

我试过这样的东西,但我卡住了:

TypedValue typedValue = new TypedValue(); 
if (this.parentActivity.getTheme().resolveAttribute(android.R.attr.windowBackground, typedValue, true))
{
  // how to get color?
}
Run Code Online (Sandbox Code Playgroud)

ash*_*hes 57

您可以通过以下方式从当前主题获取背景颜色(或Drawable):

TypedValue a = new TypedValue();
getTheme().resolveAttribute(android.R.attr.windowBackground, a, true);
if (a.type >= TypedValue.TYPE_FIRST_COLOR_INT && a.type <= TypedValue.TYPE_LAST_COLOR_INT) {
    // windowBackground is a color
    int color = a.data;
} else {
    // windowBackground is not a color, probably a drawable
    Drawable d = activity.getResources().getDrawable(a.resourceId);
}
Run Code Online (Sandbox Code Playgroud)

  • 很好的答案.如果其他人被这个绊倒,在Xamarin你必须使用Resource.Attribute.primaryAccentColor而不是,例如,Resource.Styleable.MyTheme_primaryAccentColor.这也可能适用于Android原生开发.也就是说,直接引用attr文件/对象而不是主题.我不明白其中的区别,但后者似乎是正确的选择但不是. (3认同)

Swa*_*yam 5

您可以使用来获取主题的资源:

TypedArray a = getTheme().obtainStyledAttributes(R.style.ThemeName, new int[] {R.attr.attribute_name});     
int attributeResourceId = a.getResourceId(0, 0);
Run Code Online (Sandbox Code Playgroud)

  • 它说在二进制 XML 文件的第 18 行,&lt;item&gt; 标签缺少 `android:color` 属性。 (2认同)

bat*_*eva 5

对于您的 qoustion,最简单的方法是:

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!!**
}
Run Code Online (Sandbox Code Playgroud)