How to programmatically set style attribute in a view

First of all, you don’t need to use a layout inflater to create a simple Button. You can just use:

button = new Button(context);

If you want to style the button you have 2 choices: the simplest one is to just specify all the elements in code, like many of the other answers suggest:

button.setTextColor(Color.RED);
button.setTextSize(TypedValue.COMPLEX_UNIT_SP, 18);

The other option is to define the style in XML, and apply it to the button. In the general case, you can use a ContextThemeWrapper for this:

ContextThemeWrapper newContext = new ContextThemeWrapper(baseContext, R.style.MyStyle);
button = new Button(newContext);

To change the text-related attributes on a TextView (or its subclasses like Button) there is a special method:

button.setTextAppearance(R.style.MyTextStyle);

Or, if you need to support devices pre API-23 (Android 6.0)

button.setTextAppearance(context, R.style.MyTextStyle);

This method cannot be used to change all attributes; for example to change padding you need to use a ContextThemeWrapper. But for text color, size, etc. you can use setTextAppearance.

Leave a Comment