根据当前设置的主题获取属性颜色值

8
在我的活动中,我正在维护一个SuperActivity,并在其中设置主题。
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>

现在我想在我的子活动中获取这种颜色。

正如在这个可能的答案中提到的那样,我写了以下内容:

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上下文有误吗?

1个回答

12

你有两种可能的解决方案(其中一种是你实际拥有的,但为了完备性我都包含在内):

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() 但它找不到颜色...


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接