无法以编程方式更改backgroundTint

问题描述 投票:0回答:3

Android Studio 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>

在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" />

单击按钮时,我尝试更改样式,如下所示:

dataBinding.buttonStartSearchBluetooth.setTextAppearance(R.style.buttonClickStyle)

但是它仅更改文本颜色。不变backgroundTint

为什么?

android android-button android-styles material-components material-components-android
3个回答
1
投票

尝试此代码

yourbutton.setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));

1
投票

您的风格有些问题。

  • 使用MaterialComponents.Button.* style作为父项
  • 使用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>

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

  • 更改背景颜色选择器的方法setBackgroundTintList
  • setBackgroundTintList更改文本颜色的方法

类似:

setTextColor

0
投票

button.setBackgroundTintList(ContextCompat.getColorStateList(this,R.color.button_selector)); button.setTextColor(ContextCompat.getColor(this, R.color....)); 仅关心样式TextView的文本而不是背景的样式。检查setTextAppearance以查看official doc影响的受支持属性。

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