【问题标题】:setTextAppearance - not work for MaterialButton when try to disable clicksetTextAppearance - 尝试禁用单击时不适用于 MaterialButton
【发布时间】:2020-02-23 15:47:22
【问题描述】:

Android 6.0

Android Studio 3.6

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

  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 改变了TextAppearance 而不是样式。您必须致电setTextAppearance(R.style.byttonTexAppearanceStyle)。要禁用该按钮,只需使用 button.setClickable(false)

标签: android material-design


【解决方案1】:

setTextAppearance 只关心视图文本的样式。检查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>

【讨论】:

    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 2019-07-27
    • 2021-11-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-17
    相关资源
    最近更新 更多