【问题标题】:How to change background Color to MaterialButton from android.support.design programmatically如何以编程方式将背景颜色从 android.support.design 更改为 MaterialButton
【发布时间】:2019-03-04 15:43:06
【问题描述】:

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

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

使用普通按钮,它可以工作。 有人有什么想法吗?

【问题讨论】:

  • 它至少适用于com.google.android.material:material:1.2.0-alpha03

标签: android kotlin material-design


【解决方案1】:

对于 C#/Xamarin.Android:

button.BackgroundTintList = ColorStateList.ValueOf(element.Color.ToAndroid());

【讨论】:

    【解决方案2】:

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

    使用材料设计依赖性
    implementation 'com.google.android.material:material:1.2.0-alpha05'

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        我找到了如下答案:

        我更改了以下行

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

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

        我以这种方式对其进行了测试,并且效果很好。

        【讨论】:

        • 真的正确吗? setBackgroundTintList = ... ?
        • 这对我不起作用。有没有其他办法?
        • 这消除了按钮的涟漪效应
        【解决方案5】:

        试试这个

        Drawable drawable = DrawableCompat.wrap(mButton.getBackground());
        drawable.mutate();
        DrawableCompat.setTint(drawable, getResources().getColor(R.color.my_color));
        drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        

        【讨论】:

          【解决方案6】:

          只需在材质按钮内的 XML 文件中调用此属性。

           android:backgroundTint=""
          

          【讨论】:

            【解决方案7】:

            让我们试试这个:

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

            【讨论】:

            • 这能解决问题吗?还请添加说明。
            • 为我工作,但我们将不胜感激。
            • 这一定是正确答案!
            • 它按我的意愿工作。android 中Background Color 的概念与我的想法不同。很奇怪。
            • 我收到以下代码错误:类型不匹配。必需:滤色器?找到:整数
            【解决方案8】:

            你应该改变你的 colorAccent 来改变你的 materialButton 的背景。

            不要使用 android:background 属性。 MaterialButton 管理自己的背景drawable,设置一个新的背景意味着MaterialButton 不能再保证它引入的新属性会正常工作。如果更改默认背景,MaterialButton 无法保证良好定义的行为。

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

            【讨论】:

            • 我无法更改 colorAccent,因为它会更改使用该颜色的其他组件和视图。谢谢你的回答!!
            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-12-21
            • 1970-01-01
            • 1970-01-01
            • 2011-11-08
            • 1970-01-01
            相关资源
            最近更新 更多