Fabian
Fabian

Reputation: 167

resolveAttribute always returns null for attributes

My theme:

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

This code i use to get a themed drawable:

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);
}

And this is the direct call:

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

The typedValue.resourceId is always 0 and returns no real drawable resource id, in this case it always returns R.drawable.standard_theme_not_found.

When i use this code with colors (coming from typedValue.data) its filled and does work.

How can i solve this?

Upvotes: 3

Views: 1722

Answers (2)

jonathan
jonathan

Reputation: 151

Make sure your context(Activity)'s theme has same parent as the attr's

Upvotes: 0

Fabian
Fabian

Reputation: 167

i found the answer myself, its important, that the theme is set properly in the context.

if you apply a theme programmatically:

setTheme(myTheme);

then the theme is not saved in the getBaseContext()

so you need to use

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

instead of

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

Upvotes: 1

Related Questions