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

androidkotlinmaterial-design

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?

Best Answer

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.