Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change background Color to MaterialButton from android.support.design programmatically

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?

like image 851
Gustavo Mora Avatar asked Sep 28 '18 15:09

Gustavo Mora


People also ask

How do I change the background color in MaterialButton?

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 can change button background drawable in android programmatically?

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.


1 Answers

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.

like image 134
Gustavo Mora Avatar answered Sep 19 '22 02:09

Gustavo Mora