无法以编程方式更改 backgroundTint

a_s*_*ber 2 android android-button android-styles material-components material-components-android

安卓工作室 3.6

在我的风格。xml

 <style name="buttonStyle">
        <item name="android:textColor">@color/default_button_textColor</item>
        <item name="android:backgroundTint">@color/button_bg_color</item>
        <item name="android:textSize">18sp</item>
        <item name="android:textAllCaps">true</item>
    </style>

    <style name="buttonClickStyle">
        <item name="android:textColor">@color/button_bg_color</item>
        <item name="android:backgroundTint">@color/button_click_bg_color</item>
        <item name="android:textSize">18sp</item>
        <item name="android:textAllCaps">true</item>
    </style>
Run Code Online (Sandbox Code Playgroud)

在 xml 布局中:

 <com.google.android.material.button.MaterialButton
            android:id="@+id/buttonStartSearchBluetooth"
            style="@style/buttonStyle"
            android:layout_width="0dp"
            android:layout_height="@dimen/button_height"
            android:layout_margin="@dimen/button_margin"
            android:onClick="onClickButtonStartSearch"
            android:text="@string/start_search"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent" />
Run Code Online (Sandbox Code Playgroud)

当单击按钮时,我尝试像这样更改样式:

dataBinding.buttonStartSearchBluetooth.setTextAppearance(R.style.buttonClickStyle)
Run Code Online (Sandbox Code Playgroud)

但它只改变文本颜色。没变backgroundTint

为什么?

小智 8

使用此代码更改 MaterialComponents 按钮背景色调颜色。

yourbutton.setBackgroundTintList(ColorStateList.valueOf(Color.parseColor(color)));
Run Code Online (Sandbox Code Playgroud)


Gab*_*tti 5

你的风格有些问题。

  • 使用MaterialComponents.Button.* 样式作为父项
  • 使用backgroundTint代替android:backgroundTint
  • 用于android:textAppearance定义您的文本样式

就像是:

<style name="buttonStyle" parent="@style/Widget.MaterialComponents.Button">
  <item name="android:textColor">@color/default_button_textColor</item>
  <item name="backgroundTint">@color/my_selector</item>
  <item name="android:textAppearance">@style/my_textAppearance</item>
</style>
<style name="my_textAppearance" parent="@style/TextAppearance.MaterialComponents.Button">
    <item name="android:textSize">18sp</item>
    <item name="android:textAllCaps">true</item>
</style>
Run Code Online (Sandbox Code Playgroud)

最后以编程方式更改文本颜色和背景颜色使用:

就像是:

    button.setBackgroundTintList(ContextCompat.getColorStateList(this,R.color.button_selector));
    button.setTextColor(ContextCompat.getColor(this, R.color....));
Run Code Online (Sandbox Code Playgroud)