android - setTextAppearance - 尝试禁用点击时不适用于 MaterialButton

标签 android material-design

安卓6.0

安卓工作室 3.6

在我的 fragment 中,当单击按钮时,我会像这样“即时”更改样式:

  bluetoothPageViewModel.isDisableModeLiveData().observe(this, Observer {
      dataBinding.buttonStartSearchBluetooth.setTextAppearance(
          R.style.buttonDisableStyle
      );
  })

这里的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" />

这里是 styles.xml

<style name="buttonDisableStyle" parent="@style/Widget.MaterialComponents.Button">
    <item name="android:textColor">@color/default_button_textColor</item>
    <item name="backgroundTint">@color/button_bg_color</item>
    <item name="android:enabled">false</item>
    <item name="android:clickable">false</item>
    <item name="android:textAppearance">@style/byttonTexAppearanceStyle</item>
</style>

<style name="byttonTexAppearanceStyle" parent="@style/TextAppearance.MaterialComponents.Button">
    <item name="android:textSize">18sp</item>
    <item name="android:textAllCaps">true</item>
</style>

但是在调用 setTextAppearance 之后我仍然可以点击按钮。 为什么?

最佳答案

setTextAppearance 只关心 View 文本的样式。检查official doc查看受 setTextAppearance 影响的支持属性。

您必须手动处理其他属性,检查以下内容:

bluetoothPageViewModel.isDisableModeLiveData().observe(this, Observer {
    dataBinding.buttonStartSearchBluetooth.setTextAppearance(
        R.style.byttonTexAppearanceStyle
    );

    dataBinding.buttonStartSearchBluetooth.setEnabled(false);
    dataBinding.buttonStartSearchBluetooth.setClickable(false);
    dataBinding.buttonStartSearchBluetooth.setBackgroundTintList(
        ContextCompat.getColorStateList(this, R.color.button_bg_color))
    );
})

<style name="byttonTexAppearanceStyle" parent="@style/TextAppearance.MaterialComponents.Button">
    <item name="android:textSize">18sp</item>
    <item name="android:textAllCaps">true</item>
    <item name="android:textColor">@color/default_button_textColor</item>
</style>

关于android - setTextAppearance - 尝试禁用点击时不适用于 MaterialButton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58589889/

相关文章:

android - 尝试测试 AnimatedVectorDrawable 时出错, "Can' t 从 x 到 z 变形”

android - 无法在 Android 应用程序中打开数据库

android - 在面向 ArrayIndexOutOfBoundsException 的自定义 ListView 中

android - 位图和 Android 堆

colors - Android L - SwipeRefreshLayout 配色方案的 Material 设计

android - 根据 Material 设计规范创建 "Simple Menu"

java - 如何将 onClick 用于多个 ImageView 以启动其他 Activity

java - 线性布局对于空 View 的行为如何?

java - 添加数组列表时Android Material Design下拉布局问题

javascript - 如何将卡片与左对齐文本居中对齐?