2016-02-15 14 views
2

在Android中女,我看到的getColor(INT ID)与ContextCompat.getColor(上下文的背景下,INT ID)所取代。使用ContextCompat.getColor()正确地风格基于主题

我是新来的,在Android的主题造型,所以我不知道如何正确使用此功能。目前,我在我的组织颜色的方式是通过定义,像这样的attrs:

值/ attr.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <attr name="button_bg" format="reference|color"/> 
</resources> 

然后我引用它们像这样:

值/主题.xml

<?xml version="1.0" encoding="utf-8"?> 
<resources> 
    <style name="MyTheme" parent="Theme.AppCompat.Light.NoActionBar"> 
     <item name="android:windowAnimationStyle">@null</item> 
    </style> 
    <style name="MyTheme.White"> 
     <item name="button_bg">#fff</item> 
    </style> 
    <style name="MyTheme.Black"> 
     <item name="button_bg">#000</item> 
    </style> 
</resources> 

This works。 但是,我现在如何在java中获得button_bg? 我试过ContextCompat.getColor(context, R.attr.button_bg)但这给了我一个错误Resource not found

我接近这个不正确吗?

回答

1

所看到的,问题是,比去年同期长,所以希望我仍然可以帮助其他人这一点。

您可以简单地使用id属性在你的XML:

<View 
    android:layout_height="50dp" 
    android:layout_width="50dp" 
    android:background="?attr/button_bg"> 
    ..../> 

在你的活动,你可以在设置你的主题上创建:

protected void onCreate(Bundle savedInstanceState) { 
    setTheme(R.style.your_theme);//your theme 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.your_layout); 
    .... 
} 

其余股份由机器人自动进行。

要访问通过代码,你可以使用下面的功能取决于主题的颜色:

@ColorInt 
public int getColorByAttributeId(Context context, @AttrRes int attrIdForColor){ 
    TypedValue typedValue = new TypedValue(); 
    Resources.Theme theme = context.getTheme(); 
    theme.resolveAttribute(attrIdForColor, typedValue, true); 
    return typedValue.data; 
} 

的方法简直是“愚蠢的”,这意味着有没有检查所请求的属性的颜色是一个真正的颜色资源。