在我的活动中,我保持SuperActivity
,我在其中设置主题。
public class SuperActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.MyTheme);
}
}
主题.xml
<!-- ImageBackround -->
<style name="Theme.MyTheme" parent="ThemeLight">
<item name="myBgColor">@color/translucent_black</item>
</style>
现在我想在我的一个子活动中获取这种颜色。
正如这个可能提到的answer, 我写:
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
?
您有两种可能的解决方案(一种是您实际拥有的解决方案,但为了完整起见,我将两种解决方案都包括在内):
TypedValue typedValue = new TypedValue();
if (context.getTheme().resolveAttribute(R.attr.xxx, typedValue, true))
return typedValue.data;
else
return Color.TRANSPARENT;
or
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
当然可以是任何其他默认值。是的,正如你所怀疑的,上下文是very重要的。如果您不断获得默认颜色而不是真实颜色,请检查您正在传递的上下文。我花了几个小时才弄清楚,我试图节省一些打字时间并简单地使用getApplicationContext()
但它找不到颜色...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)