17

I want to change the style of a button dynamically, i.e. in Java code, something like:

((Button)findViewById(id)).setStyle("@styles/foo")

<resources>
    <style name="foo">
        <item name="android:adjustViewBounds">true</item>
        <item name="android:maxHeight">100px</item>
        <item name="android:maxWidth">200px</item>
    </style>
</resources>

I have not seen nothing like setStyle, so:

do I have to change every single property or I can change the whole style?

jball
  • 24,791
  • 9
  • 70
  • 92
Roman
  • 1,691
  • 4
  • 18
  • 35

2 Answers2

24

To assign a style like this

<style name="ButtonHOLO" parent="android:Widget.Button">
      <item name="android:background">@drawable/btn_default_holo_dark</item>
      <item name="android:minHeight">@dimen/calc_btn_h</item>
      <item name="android:minWidth">@dimen/calc_btn_w</item>
      <item name="android:textColor">#ffffff</item>
</style>

to a button dynamically you need to use both setBackgroundResource() and setTextAppearance() functions. E.g.:

btn.setBackgroundResource(R.drawable.btn_default_holo_dark);
btn.setTextAppearance(context, R.style.ButtonHOLO);

where

btn_default_holo_dark

is a name of .xml file which describes a selector for your button.

Max
  • 389
  • 3
  • 6
4

The easiest way I found to circumvent this obvious flaw was to make two buttons. Make one of them Visibility.gone. Then simply change Visibility from the other one to gone and activate the first one by Visibility.visible.

I don't really like that solution, but it's faster and saner than the alternatives I found so far.

jsbeckr
  • 1,183
  • 1
  • 10
  • 24