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:
[code lang=”xml”]
<TextView android:id="@+id/txtName" android:text="TextView" style="@style/NameText" />
[/code]

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:
[code lang=”java”]
Button b = (Button) getLayoutInflater().inflate(R.layout.template_button, null);
b.setText(category.getName());
[/code]
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:
[code lang=”xml”]
<?xml version="1.0" encoding="utf-8"?>
<Button xmlns:android="http://schemas.android.com/apk/res/android" android:text="Date" style="@style/WhiteButton"/>
[/code]
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.

4 thoughts on “How to set styles programmatically in Android”

  1. MURTHY says:

    Good and you can even try this

    Button btn=new Button(this);
    btn.setBackgroundResource(R.drawable.greenbutton);

    where greenbutton.xml is

    </selector

    1. Gorldo says:

      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. Granjalf says:

    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?

  3. Adil says:

    Good workaround. Didn’t think of that. Great Blog/website btw.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">