【问题标题】:How to apply style to all Buttons but not to ImageButtons?如何将样式应用于所有按钮但不应用于 ImageButtons?
【发布时间】:2019-11-15 08:01:55
【问题描述】:

我需要为我的应用程序中的所有按钮应用背景颜色,所以我将其添加到 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,我不希望这样。我该如何解决这个问题?

【问题讨论】:

  • 有一个Widget.Material.ImageButton。您是否尝试过覆盖该属性并将其设置为android:imageButtonStyle

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


【解决方案1】:

ImageButton(在您的情况下为 AppCompatImageButton)使用的默认样式由 attr 在应用主题中定义:

<item name="imageButtonStyle">@style/Widget.AppCompat.ImageButton</item>

在这种样式中,背景属性&lt;item name="background"&gt;@drawable/btn_default_material&lt;/item&gt; 被着色为android:tint="?attr/colorButtonNormal"

您可以对ImageButton 使用从btn_default_material 开始的自定义样式,也可以覆盖布局中的颜色。
比如:

<ImageButton  
     android:theme="@style/MyImageButtonTheme"/> 

类似:

  <style name="MyImageButtonTheme" parent="ThemeOverlay.AppCompat.Light"> 
      <item name="colorButtonNormal">@color/my_color</item> 
 </style>

还评估迁移到材料组件和MaterialButton。 在这种情况下,仅使用样式覆盖颜色非常简单:

  <style name="MyButtonTheme" parent="Widget.MaterialComponents.Button">
    <item name="materialThemeOverlay">@style/ButtonStylePrimaryColor</item>
  </style>

  <style name="ButtonStylePrimaryColor">
    <item name="colorPrimary">@color/....</item>
  </style>

【讨论】:

    【解决方案2】:

    您可以通过为不同的视图应用不同的样式来做到这一点

    假设我有三种不同颜色组合的样式,我希望为所有大按钮应用 bigButtonTheme 样式

    然后

    我在所有大按钮上添加这一行android:theme="@style/bigButtonTheme"&gt;

    休息按钮或其他 vewis 将保持不变。 您还可以通过定义为父主题来复制样式的其他属性,例如全局主题字体背景颜色

    <style name="ButtonColor" parent="@style/GlobelStyleOfApp"/>
    

    【讨论】:

      猜你喜欢
      • 2012-07-08
      • 2011-01-25
      • 2013-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      • 1970-01-01
      • 2017-12-30
      相关资源
      最近更新 更多