我需要为应用程序中的所有按钮应用背景色,因此我将其添加到 styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- button styles -->
<item name="colorButtonNormal">@color/button_color</item> <!-- below api 21 -->
<item name="android:colorButtonNormal">@color/button_color</item> <!-- above api 21 -->
<item name="android:buttonStyle">@style/ButtonColor</item>
</style>
<style name="ButtonColor" parent="@style/Widget.AppCompat.Button">
<item name="android:textColor">@color/font</item>
</style>
效果很好,当我在 XML 中添加一个按钮时,该按钮自动具有我在 styles.xml 中设置的颜色
问题是,当我添加一个 ImageButton 时,ImageButton 也会获得那些颜色,而我不希望这样。问题特别出在 colorButtonNormal
上,它也将背景颜色应用于 ImageButton,我不希望这样。我该如何解决这个问题?
最佳答案
ImageButton
使用的默认样式(在您的情况下 AppCompatImageButton
)由 attr 在应用程序主题中定义:
<item name="imageButtonStyle">@style/Widget.AppCompat.ImageButton</item>
在此样式中,背景属性 <item name="background">@drawable/btn_default_material</item>
用 android:tint="?attr/colorButtonNormal"
染色.
您可以使用从 btn_default_material
开始的自定义样式对于 ImageButton
或者您可以覆盖布局中的颜色。
像这样的东西:
<ImageButton
android:theme="@style/MyImageButtonTheme"/>
用类似的东西:
<style name="MyImageButtonTheme" parent="ThemeOverlay.AppCompat.Light">
<item name="colorButtonNormal">@color/my_color</item>
</style>
同时评估迁移到 Material Components 和 MaterialButton
.
在这种情况下,仅使用样式覆盖颜色非常简单:
<style name="MyButtonTheme" parent="Widget.MaterialComponents.Button">
<item name="materialThemeOverlay">@style/ButtonStylePrimaryColor</item>
</style>
<style name="ButtonStylePrimaryColor">
<item name="colorPrimary">@color/....</item>
</style>
关于android - 如何将样式应用于所有按钮而不是 ImageButtons?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58872635/