I\'m getting a view from the XML with the code below:
Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);
I made a helper interface for this using the holder pattern.
public interface StyleHolder {
void applyStyle(V view);
}
Now for every style you want to use pragmatically just implement the interface, for example:
public class ButtonStyleHolder implements StyleHolder
Declare a stylable in your attrs.xml
, the styleable for this example is:
Here is the style declared in styles.xml
:
And finally the implementation of the style holder:
Button btn = new Button(context);
StyleHolder
I found this very helpful as it can be easily reused and keeps the code clean and verbose, i would recommend using this only as a local variable so we can allow the garbage collector to do its job once we're done with setting all the styles.