在我的 Activity 中,我正在维护一个 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>
现在我想在我的一个子 Activity 中获取这种颜色。
如本可能 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;
或
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()
但它没有找到颜色......
关于android - 根据当前设置的主题获取属性颜色值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23320577/