创建从应用程序主题中设置的默认样式扩展的样式

时间:2019-05-29 19:19:38

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

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

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

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

2 个答案:

答案 0 :(得分:0)

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

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

希望您能得到答案。如果没有,请解释您的问题。

答案 1 :(得分:0)

如果除了您的自定义默认按钮样式外还出现了大写,则无需将大写样式设为?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样式(大写文本)。

相关问题