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
只关心样式化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>