How to set styles programmatically in Android

When you’re using different kind of styles in your project, the best way to accomplish this is to use the styles.xml file where you can define different style definitions for your views. These styles can be applied very easily, like:

<TextView android:id="@+id/txtName" android:text="TextView" style="@style/NameText" />

This is all done, using declarative xml syntax. But what if you are forced to create views programmatically?
There is no view.setStyle(“NameText”) method, so how do can we define them in code?
There is a small workaround which might come in handy:
Final syntax:

Button b = (Button) getLayoutInflater().inflate(R.layout.template_button, null);

This code is creating a button, using the layoutinflator method. This method is using xml layout template to use a base for the button.

This layout file is looking like this:

<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="" android:text="Date" style="@style/WhiteButton"/>

As you can see, just a definition of a button with style included.

All quit simple but very powerfull. If you’ve to use styling programmatically, this is a option. The downside is that you have to create layouts for each option. But if you’re using just a few options, this surely is the way to go!
Besides that, it’s very maintainable.


I'm a webdeveloper, looking for the best experience, working between development and design. Just a creative programmer. When I'm getting tired of programming C#, i'd love to create 3D images in 3D Studio Max, play the guitar, create an app for Android or crush some plastics on a climbing wall or try to stay alive when i´m descending some nice white powdered snowy mountains on my snowboard.

5 thoughts to “How to set styles programmatically in Android”

  1. Good and you can even try this

    Button btn=new Button(this);

    where greenbutton.xml is


    1. The UI of Google App on the iPhone sohuld be revised to mirror Android’s VoiceSe. Switching from searching ‘Web’ to searching ‘Maps’ is not as easy as it appears to be in Android, and at least not as easy as it sohuld be.

  2. That means that if I want to have styles for more than 1 widget I will need to create a xml for each of them?

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.