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?
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 .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With