I am trying myself to set style properties obtained from my Theme in code.
My reason is that I want to use a style from my own Theme, BUT my User Interface Layout is entirely generated in code( using a custom layout builder), without defining any widgets in XML. So I cannot set a style in the XML layout of my widget – there isn’t any XML layout.
I am thinking that I will be able to set this style in the code of my widget by using
TypedArray a =
context.obtainStyledAttributes(AttributeSet
set, int[] attrs, int defStyleAttr, int defStyleRes)
Here it seems (to me) that
AttributeSet set = null; because this is what the XML inflater would have provided.
int[] attrs = R.styleable.MyWidget; defines what attributes I want to look at.
int defStyleAttr = myWidgetStyle; which is a reference, defined in my Theme, to a style for MyWidget. These are both defined in XML files in res/values.
“myWidgetStyle” follows the pattern of name the android developers have used in their code.
defStyleRes = 0; I am hoping that I don’t need to think about this.
Then to get any property , such as a background color,
Color color = a.getColor(R.styleable.MyWidget_background, R.color.my_default);
a.recycle();
This does seem to work –so far anyway.
It seems that the android build system conveniently generates the correct index to use in a.getColor, and names it R.styleable.MyWidget_background . I didn’t make this name, so Android must have done it using my XML for my styleable MyWidget.
I expect one can look up the correct index by searching the TypedArray for the required attribute , but that would be inefficient and the TypedArray looks like an unpleasant contraption to deal with. I would use a very long stick to poke it!
Don