如何以编程方式更改 Android 中 Material 组件文本按钮的样式?

How do I programmatically change the style of a Material Component Text Button in Android?

我有一个 material 文本按钮 <Button android:id="@+id/button" style="@style/Widget.MaterialComponents.Button.TextButton"/>,我想在运行时更改它的颜色。所以我使用 button.setTextColor(Color.rgb(10, 10, 10)) 设置文本颜色。不幸的是,这并没有改变可绘制的背景,所以当我点击按钮时,它的波纹颜色没有改变。我猜我需要用 attackButton.background = getDrawable(R.drawable.ripple) 之类的东西更改背景,但我不确定如何填充 ripple.xml。这种方法对更改按钮文本颜色和波纹有意义吗?如果是这样,我应该怎么写ripple.xml

你试过RippleDrawable? Then just Button.setBackground() to different resource or even a selectorxml了吗?如果带有选择器的波纹对您来说不够,可以设置波纹遮罩本身

myRipple.xml

<ripple android:color="#ffff0000">
   <item android:id="@android:id/myRippleMask"
         android:drawable="@android:color/white" />
</ripple>

以编程方式:

LayerDrawable myRipple = ContextCompat.getDrawable(context, drawable.myRipple.xml);
myRipple.setDrawableByLayerId(R.id.myRippleMask,Color.rgb(10, 10, 10));

每个面具都是不同的颜色

要更改 MaterialButton 中的颜色,您可以使用:

  • button.setBackgroundTintList 更改背景色调。你应该使用选择器。
  • button.setRippleColor 改变波纹颜色。同样在这种情况下,您应该使用选择器(见下文)
  • button.setTextColor 改变文字的颜色。同样在这种情况下,您应该使用选择器。

这是波纹颜色中使用的默认选择器:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

  <item android:alpha="@dimen/mtrl_low_ripple_pressed_alpha" android:color="?attr/colorPrimary" android:state_pressed="true"/>
  <item android:alpha="@dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true" android:state_hovered="true"/>
  <item android:alpha="@dimen/mtrl_low_ripple_focused_alpha" android:color="?attr/colorPrimary" android:state_focused="true"/>
  <item android:alpha="@dimen/mtrl_low_ripple_hovered_alpha" android:color="?attr/colorPrimary" android:state_hovered="true"/>
  <item android:alpha="@dimen/mtrl_low_ripple_default_alpha" android:color="?attr/colorPrimary"/>

</selector>

Textcolor、backgroundcolor 和 ripplecolor 的一行代码编程无资源文件方法:

 MaterialButton myMaterialButton = new MaterialButton(this);
 myMaterialButton.setTextColor(Color.RED);
 myMaterialButton.setBackgroundColor(Color.GRAY);
 myMaterialButton.setRippleColor(ColorStateList.valueOf(Color.RED));