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
为什么?
尝试此代码
yourbutton.setBackgroundTintList(contextInstance.getResources().getColorStateList(R.color.your_xml_name));
您的风格有些问题。
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
button.setBackgroundTintList(ContextCompat.getColorStateList(this,R.color.button_selector));
button.setTextColor(ContextCompat.getColor(this, R.color....));
仅关心样式TextView的文本而不是背景的样式。检查setTextAppearance
以查看official doc影响的受支持属性。