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

问题描述 投票:1回答:2

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

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

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

android kotlin material-design
2个回答
10
投票

我找到了答案如下:

我更改了以下行

materialButton.setBackgroundColor( ContextCompat.getColor(this@MyActivity, R.color.myCustomColor));

materialButton.setBackgroundTintList = ContextCompat.getColorStateList(this@MyActivity, R.color.myCustomColor)

我用那种方式测试它并且它工作得很好。


1
投票

让我们试试这个:

mButton.getBackground().setColorFilter(getResources().getColor(R.color.indian_red), PorterDuff.Mode.SRC_ATOP);

0
投票

您应该更改colorAccent以更改materialButton的背景。

不要使用android:background属性。 MaterialButton管理自己的背景drawable,并设置新的背景意味着MaterialButton不再能保证它引入的新属性能够正常运行。如果更改了默认背景,则MaterialButton无法保证定义明确的行为。

对于填充按钮,此类使用主题的?attr / colorAccent作为背景色调颜色,使用白色作为文本颜色。对于未填充按钮,此类使用?attr / colorAccent作为文本颜色,使用透明作为背景色调。

© www.soinside.com 2019 - 2024. All rights reserved.