How to programmatically set style attribute in a view

Lint_ picture Lint_ · Jan 6, 2010 · Viewed 226.9k times · Source

I'm getting a view from the XML with the code below:

Button view = (Button) LayoutInflater.from(this).inflate(R.layout.section_button, null);

I would like to set a "style" for the button how can I do that in java since a want to use several style for each button I will use.

Answer

Christopher Orr picture Christopher Orr · Jan 6, 2010

Generally you can't change styles programmatically; you can set the look of a screen, or part of a layout, or individual button in your XML layout using themes or styles. Themes can, however, be applied programmatically.

There is also such a thing as a StateListDrawable which lets you define different drawables for each state the your Button can be in, whether focused, selected, pressed, disabled and so on.

For example, to get your button to change colour when it's pressed, you could define an XML file called res/drawable/my_button.xml directory like this:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item
    android:state_pressed="true"
    android:drawable="@drawable/btn_pressed" />
  <item
    android:state_pressed="false"
    android:drawable="@drawable/btn_normal" />
</selector>

You can then apply this selector to a Button by setting the property android:background="@drawable/my_button".