I was recently looking for a way to set the style for a view programmatically. I found some solutions that I am going to share them here with you.

Libraries:

Of course, there is always a library for anything that you are looking for :)

I found the following library useful for changing the style of an existing view:

For changing style with library you just have to do it like:

myView.style(R.style.MyStyle)

Without Libraries:

If you are not a fan of adding external libraries to your project(like me) then I can suggest a simple solution. you can still specify a style for your view, but problem is that you have to create your view programmatically and can't change the style for a view in an XML file.

So all you have to do is to pass your style to the view while initializing it. like the following:

Button(context, null, R.style.AppTheme_ButtonPrimary)

I realized that there are some issues with styling some views in this way. For instance, this solution doesn't work with Material Design views(for instance: MaterialButton). For those views, you can use `ContextThemeWrapper`.

val newContext = ContextThemeWrapper(

context,

R.style.AppTheme_ButtonPrimary

)



val button = MaterialButton(newContext)

I hope this article helps to resolve some issues. And please comment if you know some more solutions regarding the topic.

Cheers!