【问题标题】:Create style that extends from default style set in application theme创建从应用程序主题中设置的默认样式扩展的样式
【发布时间】:2019-05-29 19:19:37
【问题描述】:

我已在我的应用程序主题中设置了默认按钮样式,以便将其应用于应用程序中的每个按钮。
除了默认样式外,很少有按钮需要将其文本大写。所以我想做的是这样的
(以下代码 sn-p 不起作用,因为我无法设置parent="?attr/materialButtonStyle"):

<style name="capitalizedButton" parent="?attr/materialButtonStyle">
    <item name="android:textAllCaps">true</item>
</style>

是否可以扩展在 theme.xml 中定义的样式?我不想引用我在主题中设置的本地样式,因为以后可能会更改,而是打算使用主题属性访问它。

【问题讨论】:

    标签: android material-design android-theme material-theme


    【解决方案1】:

    如果除了您的自定义默认按钮样式之外还发生了大写,则无需将大写样式设为?attr/materialButtonStyle 的子项(这无论如何都无法完成,因为?attr 引用了当前应用主题中的属性)。你可以阅读更多关于它的信息here

    styles.xml

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="buttonStyle">@style/DefaultButton</item>
    </style>
    
    <style name="DefaultButton" parent="Widget.AppCompat.Button">
        <item name="android:textColor">@color/white</item>
    </style>
    
    <style name="AllCapsButton">
        <item name="android:textAllCaps">true</item>
    </style>
    

    layout.xml

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:theme="@style/AllCapsButton"/>
    

    在上面的代码中,button 获取主题应用的DefaultButton 样式(白色文本),以及布局文件中应用的AllCapsButton 样式(大写文本)。

    【讨论】:

    • 太棒了,不知道自定义样式应用于默认样式。谢谢!
    • 也感谢您的提问。研究起来很有趣。?attr 不是最容易掌握的概念。
    【解决方案2】:

    您可以直接将样式传递给 XML 中的 Button 小部件,例如:

    <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            style="capitalizedButton"/>
    

    希望你能得到答案。如果不是,请解释您的问题。

    【讨论】:

    • 好吧,我的问题是如何从主题样式中扩展。创建主题时我无法设置parent="?attr/materialButtonStyle"。我想知道是否有其他方法可以实现。
    猜你喜欢
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2017-02-04
    • 1970-01-01
    相关资源
    最近更新 更多