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

时间:2012-09-11 18:31:31

标签: android

我试过这样的事,但我坚持了下来:

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

3 个答案:

答案 0 :(得分:55)

您可以通过以下方式从当前主题中获取背景颜色(或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);
}

答案 1 :(得分:4)

您可以使用以下方式获取主题资源:

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

答案 2 :(得分:3)

对于你的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!!**
}