How can I change the button style dynamically in Android?

I want to change the button style dynamically, that is, in Java code, for example:

((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 anything like setStyle, therefore:

Do I need to change every single property, or can I change the whole style?

+7
source share
4 answers
+1
source

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> 

the button dynamically needs to use the setBackgroundResource () and setTextAppearance () functions. For example:.

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

Where

btn_default_holo_dark

is the name of the .xml file that describes the selector for your button.

+11
source

The easiest way I've found to get around this obvious flaw is to make buttons. Make one of them Visibility.gone . Then just change Visibility from another to gone and activate the first to Visibility.visible .

I really don't like this solution, but it is faster and safer than the alternatives I have found so far.

+1
source

You can also take a look at 9 patch images. They are very useful for adjusting the size and text of the image attached to your widget or button based on the current device on which your application is running.

9 patch

9 patch installation tool

0
source

All Articles