tags:

views:

1574

answers:

1

I'm getting a view from 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.

Thanks in advance,

Lint_

+2  A: 

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"&gt;
  <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".

Christopher
My problem is that I load data from a webservice that describe my button info. The buttons need to have different style based on a category they belong. That's why I would like to set style dynamicly.
Lint_
Well you can't change the Android `style` attribute, but you can programmatically set the background of an `Button` like you can with any other view, if that will suffice. Also, as a `Button` inherits from `TextView`, you can change text properties. Just look at the API documentation for these items... http://developer.android.com/reference/android/view/View.html#setBackgroundResource%28int%29
Christopher
I was just thinking about doing that, right before checking if I had new answers. Thanks a lot.
Lint_