如何将样式应用于所有按钮,而不应用于图像按钮?

问题描述 投票:0回答:2

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

谢谢

我需要为应用程序中的所有按钮应用背景色,所以我将其添加到styles.xml中。

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>

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

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

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

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

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

然后

我将此行添加到所有大按钮android:theme="@style/bigButtonTheme">

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

<style name="ButtonColor" parent="@style/GlobelStyleOfApp"/>
android android-layout android-button imagebutton android-styles
2个回答
2
投票

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


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.