我们会根据当前的一组主题ATTR颜色值 [英] Get attr color value based on current set theme
问题描述
在我的活动,我保持了超活性
,其中我设置的主题。
In my activity I'm maintaining a SuperActivity
, in which I'm setting the theme.
public class SuperActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.MyTheme);
}
}
的themes.xml
<!-- ImageBackround -->
<style name="Theme.MyTheme" parent="ThemeLight">
<item name="myBgColor">@color/translucent_black</item>
</style>
现在我想在我的子活动之一,获取这种颜色。
Now I want to fetch this color in one of my child activity.
如在本可能回答提到我写道:
As mentioned in this probable answer, I wrote:
int[] attrs = new int[] { R.attr.myBgColor /* index 0 */};
TypedArray ta = ChildActivity.this.obtainStyledAttributes(attrs);
int color = ta.getColor(0, android.R.color.background_light);
String c = getString(color);
ta.recycle();
但每次我得到的默认值的值 android.R.color.background_light
&安培;没有 R.attr.myBgColor
的
我哪里做错了。上午我路过的错误的上下文 ChildActivity.this
Where I'm doing wrong. Am I passing the wrong context of ChildActivity.this
?
推荐答案
您有两种可能的解决方案(一个是你确实有,但是我包括为完整起见):
You have two possible solutions (one is what you actually have but I include both for the sake of completeness):
TypedValue typedValue = new TypedValue();
if (context.getTheme().resolveAttribute(R.attr.xxx, typedValue, true))
return typedValue.data;
else
return Color.TRANSPARENT;
或
int[] attribute = new int[] { R.attr.xxx };
TypedArray array = context.getTheme().obtainStyledAttributes(attribute);
int color = array.getColor(0, Color.TRANSPARENT);
array.recycle();
return color;
Color.TRANSPARENT
可以是任何其他默认是肯定的。是的,正如你怀疑的背景下为非常重要。如果你一直得到默认的颜色,而不是真实的,看看你是路过什么情况下。我花了几个小时的数字出来,我想腾出一些打字,只是用 getApplicationContext()
,但它没有找到的颜色,然后...
Color.TRANSPARENT
could be any other default for sure. And yes, as you suspected, the context is very important. If you keep getting the default color instead of the real one, check out what context you are passing. It took me several hours to figure it out, I tried to spare some typing and simply used getApplicationContext()
but it doesn't find the colors then...
这篇关于我们会根据当前的一组主题ATTR颜色值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!