I try change color to MaterialButton with this code:
var materialButton = findViewByid(R.id....) as MaterialButton
materialButton.setBackgroundColor( ContextCompat.getColor(this@MyActivity, R.color.myCustomColor));
With a normal Button, it works. Anyone have any ideas?
With the MaterialButton you have 2 options: Using the backgroundTint attribute as suggest by Zaid Mirza. If you want to override some theme attributes from a default style you can use new materialThemeOverlay attribute. It is the best option in my opinion.
How to set Background of button in Android programmatically? setBackgroundResource() method is used to change the button background programmatically. setBackgroundResource(int id) accepts id of drawable resource and applies the background to the button.
I found the answer which is as below:
I changed the following line
materialButton.setBackgroundColor( ContextCompat.getColor(this@MyActivity, R.color.myCustomColor));
to
materialButton.setBackgroundTintList(ContextCompat.getColorStateList(this@MyActivity, R.color.myCustomColor));
I tested it that way and it worked perfectly.
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