android - 如何将样式应用于所有按钮而不是 ImageButtons?

标签 android android-layout android-button imagebutton android-styles

我需要为应用程序中的所有按钮应用背景色,因此我将其添加到 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/

相关文章:

java - 在 Java 代码中为 Android 添加按钮

java - rsSendToClient 失败并出现异常

android - 这是普通的 Android 通知 (RemoteView) 布局吗?

android - 在对话框布局的属性中使用 "onclick"android

android - 未定义 layoutweight 属性时 View 消失

android - 按钮不引起 onClick 事件

Android 切换按钮 - Material 设计

android - 如何编写成功构建后确实提交当前分支的gradle脚本

android - 如何在 Android TabLayout 中监听滚动事件

android - 当我返回事件时触发事件