Access resource defined in theme and attrs.xml android

前端 未结 5 1956
情歌与酒
情歌与酒 2020-12-04 21:55

I have a scenario in which I want to set a Drawable depending upon the theme defined.

To explain this further, Here is what I have in code:

5条回答
  •  既然无缘
    2020-12-04 22:36

    Here are the results of my investigation, regarding this topic. If we have declare-stylable then we can override those values in themes.

    So far the best way that I found how to get them is the following.

    TypedArray a = context.getTheme().obtainStyledAttributes(R.styleable.AppTheme);
    a.getDrawable(R.styleable.AppTheme_homeIcon);
    

    By using R.styleable.AppTheme_homeIcon we are referencing exactly that attribute that we want. For example if we would have few more attributes, then we can reference them as follows:

    a.getColor(R.styleable.AppTheme_color,defaultValue);
    a.getDimension(R.styleable.AppTheme_width,defaultWidth);
    

    And if in current theme those attributes were not defined you will get default values and no Exceptions.

提交回复
热议问题