2017-01-26 101 views
0

我的主題:resolveAttribute總是返回null屬性

<style name="AppThemeDark" parent="Theme.AppCompat"> 
    <item name="AppButton">@drawable/standard_dark_button_selector</item> 
</style>  

此代碼我用它來獲得一個主題繪製:

public static Drawable getThemedDrawable(Context context, int resource) { 
    TypedValue typedValue = new TypedValue(); 
    Resources.Theme theme = context.getTheme(); 
    theme.resolveAttribute(resource, typedValue, true); 
    if(typedValue.resourceId == 0) { 
     return context.getResources().getDrawable(R.drawable.standard_theme_not_found); 
    } 
    else 
     return context.getResources().getDrawable(typedValue.resourceId); 
} 

這就是直接調用:

positive.setBackgroundDrawable(Theme.getThemedDrawable(getBaseContext(), R.attr.AppButton)); 

typedValue.resourceId始終爲0,並且不返回實際的可繪製資源ID,在這種情況下,它總是返回R.drawable.standard_theme_not_f ound。

當我用這個代碼的顏色(來自typedValue.data)它的填充和工作。

我該如何解決這個問題?

回答

-1

我發現自己的答案,其重要的是,主題在上下文中正確設置。

如果應用程序一個主題:

setTheme(myTheme); 

那麼主題不會保存在getBaseContext()

,所以你需要使用

Theme.getThemedDrawable(myActivity, R.attr.AppContainer1Background) 

,而不是

Theme.getThemedDrawable(getBaseContext(), R.attr.AppContainer1Background)