Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change a button style dynamically in Android? [duplicate]

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?

like image 369
DarthRoman Avatar asked Jan 19 '11 17:01

DarthRoman


People also ask

Can we change the shape of button in Android Studio?

We can set custom shapes on our button using the xml tag <shape> . These xml files are created in the drawable folder too. shape can be used inside selectors . The shape can be set to rectangle (default), oval , ring , line .

How many types of buttons are there in Android?

In android, we have a different type of buttons available to use based on our requirements, those are ImageButton, ToggleButton, RadioButton. In android, we can create a Button control in two ways either in the XML layout file or create it in the Activity file programmatically.


1 Answers

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.

like image 62
Max Avatar answered Oct 11 '22 03:10

Max