【问题标题】:Adding button style to AppTheme not working将按钮样式添加到 AppTheme 不起作用
【发布时间】:2019-09-12 19:21:03
【问题描述】:

我尝试向我的 AppTheme 添加自定义按钮样式,但它不起作用。作为参考,我在我的 AppTheme 中添加了 Spinner 样式,它运行良好。所以,我只需要找出我的按钮样式哪里出了问题。

style.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:spinnerStyle">@style/mySpinnerStyle</item>
    <item name="android:buttonStyle">@style/myButtonStyle</item>
    <item name="buttonStyle">@style/myButtonStyle</item>
</style>

<style name="mySpinnerStyle" parent="@style/Widget.AppCompat.Spinner">
    <item name="overlapAnchor">true</item>
    <item name="android:background">@drawable/spinner_background</item>
    <item name="android:padding">5sp</item>
</style>

<style name="myButtonStyle" parent="@style/Widget.AppCompat.Button">
    <item name="android:background">@drawable/button_states</item>
    <item name="android:focusable">true</item>
    <item name="android:clickable">true</item>
</style>

如果需要,我可以添加我的 button_states.xml 文件,但如果我将样式直接插入到布局中的按钮属性中,则该样式有效,如下所示:

<Button
    android:id="@+id/button_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="4"
    style="@style/myButtonStyle"
    android:textSize="@dimen/text_size"
    android:text="OK" />

父布局中的声明:

android:theme="@style/AppTheme"

那么,为什么它直接在按钮属性中起作用,而不是通过我的 AppTheme?

【问题讨论】:

  • 主题的父级不需要@style。并尝试将应用主题留在清单中,更易于管理
  • 感谢您的反馈。我应用了您的建议,现在一切正常。从“myButtonStyle”上的父级删除@style 使其工作。虽然样式更改不会显示在 IDE 的预览中,但它只会在运行应用程序时显示。有什么想法吗?

标签: android button styles themes


【解决方案1】:

1- 在你的 android studio 中右键单击 res / drawable 文件创建新的 DRAWABLE RESOUCE 文件

2- 在里面写这样的代码:-

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
    <corners
android:radius="100dp"
        />
    <solid
        android:color="#FFFFFF"

        />
    <size
        android:width="100dp"
        android:height="100dp"
        />

</shape>

3- 打开包含此按钮的 XML 文件并将按钮的背景更改为您之前创建的可绘制对象

【讨论】:

  • 谢谢,是的,我的按钮有一个类似的文件。我没有显示该文件,因为我知道错误出现在我显示的代码中。
【解决方案2】:

感谢 Ahmad Sattout 的回答。

在我的按钮样式中,我从父级中删除了@style:

原文:

<style name="myButtonStyle" parent="@style/Widget.AppCompat.Button">
    <item name="android:background">@drawable/button_states</item>
    <item name="android:focusable">true</item>
    <item name="android:clickable">true</item>
</style>

改变了:

<style name="myButtonStyle" parent="Widget.AppCompat.Button">
    <item name="android:background">@drawable/button_states</item>
    <item name="android:focusable">true</item>
    <item name="android:clickable">true</item>
</style>

如果有人能更详细地解释为什么会发生这种情况,将不胜感激。

【讨论】:

  • 只是编译错误。风格往往不会告诉你什么是错的或什么是不正确的。您添加了@style,但工作室不知道这是对还是错
猜你喜欢
  • 1970-01-01
  • 2023-03-26
  • 1970-01-01
  • 1970-01-01
  • 2021-10-05
  • 1970-01-01
  • 2020-01-12
  • 2017-10-28
  • 2017-07-02
相关资源
最近更新 更多