【问题标题】:How do I programmatically change the style of a Material Component Text Button in Android?如何以编程方式更改 Android 中材质组件文本按钮的样式?
【发布时间】:2020-06-06 22:08:08
【问题描述】:

我有一个材质文本按钮<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

【问题讨论】:

    标签: android android-button material-components-android material-components


    【解决方案1】:

    要更改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>
    

    【讨论】:

    • 谢谢 :) 我忘记将按钮转换为 MaterialButton,所以我看不到这些方法! (button as MaterialButton).rippleColor = getColorStateList(R.color.button_secondary)。另外,我将 alpha 设置为 .12,因为 @dimen alpha 是私有的。
    【解决方案2】:

    你试过RippleDrawable吗?然后只需 Button.setBackground() 到不同的资源,甚至是 selector xml。如果带有选择器的波纹对您来说还不够,可以设置波纹掩码本身

    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));
    

    每个面具都是不同的颜色

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 2012-02-29
        • 1970-01-01
        • 1970-01-01
        • 2016-07-13
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        • 2019-05-28
        相关资源
        最近更新 更多