不能使用主题改变按钮背景

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

我想在我的应用程序中为一个Button设置自定义样式,但我尝试设置一个自定义主题,但没有成功。例如,这并没有改变背景

<Button
  android:theme="@style/CustomTheme"
  ... />

<style name="CustomTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   <item name="android:background">@color/colorPrimary</item>
</style>

如果我使用样式做同样的事情,它可以正常工作。

android android-layout android-theme android-styles
1个回答
1
投票

发生的情况是,背景属性被默认的 Button. 默认的风格是在你的主题中设置的,如果你看一看 Theme.AppCompat.Light.DarkActionBar (你要继承的主题)你会看到下面的继承结构。

Theme.AppCompat.Light.DarkActionBar
    Base.Theme.AppCompat.Light.DarkActionBar
        Base.Theme.AppCompat.Light
            Base.V7.Theme.AppCompat.Light

Base.V7.Theme.AppCompat.Light 你会发现 buttonStyle 属性的定义,这也是 Button 元素。

<item name="buttonStyle">@style/Widget.AppCompat.Button</item>

同样,如果你看一下 Widget.AppCompat.Button 你会发现它继承了 Base.Widget.AppCompat.Button 并且它设定了 android:background 属性(在其他属性之间)。

所以,为了改变这个属性的风格,我们可以使用 Button 在一个主题中,你应该使用 buttonStyle 属性。最保险的做法是创建一个新的样式,继承自 Widget.AppCompat.Button (这样你就不会失去正在那里设置的所有其他属性)并在那里设置android:background属性。

<style name="CustomStyle" parent="Widget.AppCompat.Button">
    <item name="android:background">@color/colorPrimary</item>
</style>

<style name="CustomTheme" parent="Theme.AppCompat.Light.DarkActionBar">
   <item name="buttonStyle">@style/CustomStyle</item>
</style>
© www.soinside.com 2019 - 2024. All rights reserved.