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

我尝试了这样的事情,但我坚持:

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

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

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

 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); } 

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

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

最简单的方法是:

 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!!** }