Non of the provided answers are correct.
You CAN set style programatically.
Short answer is take a look at http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/content/Context.java#435
Long answer.
Here's my snippet to set custom defined style programatically to your view:
1) Create a style in your styles.xml file
<style name="MyStyle">
<item name="customTextColor">#39445B</item>
<item name="customDividerColor">#8D5AA8</item>
</style>
Do not forget to define your custom attributes in attrs.xml file
My attrsl.xml file:
<declare-styleable name="CustomWidget">
<attr name="customTextColor" format="color" />
<attr name="customDividerColor" format="color" />
</declare-styleable>
Notice you can use any name for your styleable (my CustomWidget)
Now lets set the style to the widget Programatically
Here's My simple widget:
public class StyleableWidget extends LinearLayout {
private final StyleLoader styleLoader = new StyleLoader();
private TextView textView;
private View divider;
public StyleableWidget(Context context) {
super(context);
init();
}
private void init() {
inflate(getContext(), R.layout.widget_styleable, this);
textView = (TextView) findViewById(R.id.text_view);
divider = findViewById(R.id.divider);
setOrientation(VERTICAL);
}
protected void apply(StyleLoader.StyleAttrs styleAttrs) {
textView.setTextColor(styleAttrs.textColor);
divider.setBackgroundColor(styleAttrs.dividerColor);
}
public void setStyle(@StyleRes int style) {
apply(styleLoader.load(getContext(), style));
}
}
layout:
<TextView
android:id="@+id/text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="22sp"
android:layout_gravity="center"
android:text="@string/styleble_title" />
<View
android:id="@+id/divider"
android:layout_width="match_parent"
android:layout_height="1dp"/>
</merge>
And finally StyleLoader class implementation
public class StyleLoader {
public StyleLoader() {
}
public static class StyleAttrs {
public int textColor;
public int dividerColor;
}
public StyleAttrs load(Context context, @StyleRes int styleResId) {
final TypedArray styledAttributes = context.obtainStyledAttributes(styleResId, R.styleable.CustomWidget);
return load(styledAttributes);
}
@NonNull
private StyleAttrs load(TypedArray styledAttributes) {
StyleAttrs styleAttrs = new StyleAttrs();
try {
styleAttrs.textColor = styledAttributes.getColor(R.styleable.CustomWidget_customTextColor, 0);
styleAttrs.dividerColor = styledAttributes.getColor(R.styleable.CustomWidget_customDividerColor, 0);
} finally {
styledAttributes.recycle();
}
return styleAttrs;
}
}
You can find fully working example at https://github.com/Defuera/SetStylableProgramatically