如何以编程方式从android.support.design将背景颜色更改为MaterialButton

Gus*_*ora 4 android kotlin material-design

我尝试使用以下代码将颜色更改为MaterialButton:

var materialButton = findViewByid(R.id....) as MaterialButton
materialButton.setBackgroundColor( ContextCompat.getColor(this@MyActivity, R.color.myCustomColor));
Run Code Online (Sandbox Code Playgroud)

使用普通按钮,它可以工作.有人有主意吗?

Gus*_*ora 16

我找到了答案.我改变

materialButton.setBackgroundColor( ContextCompat.getColor(this@MyActivity, R.color.myCustomColor));
Run Code Online (Sandbox Code Playgroud)

对于

materialButton.setBackgroundTintList = ContextCompat.getColorStateList(this@MyActivity, R.color.myCustomColor)
Run Code Online (Sandbox Code Playgroud)

我以这种方式测试并且完美地工作


Tar*_*rma 16

只需在 Material Button 内的 XML 文件中调用此属性。

 android:backgroundTint=""
Run Code Online (Sandbox Code Playgroud)


mil*_*tus 7

让我们试试这个:

mButton.getBackground().setColorFilter(getResources().getColor(R.color.indian_red), PorterDuff.Mode.SRC_ATOP);
Run Code Online (Sandbox Code Playgroud)