首页 > 解决方案 > 如何在不使用xml的情况下修改材质组件的主题?

问题描述

<com.google.android.material.button.MaterialButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/ThemeOverlay.Life.Red" />

我们可以使用android:theme="***".

但我想在 Java/Kotlin 代码中修改主题。

MaterialButton button= ...
button.setTheme(...)

可惜没有setTheme办法……

标签: androidmaterial-components-androidmaterialbutton

解决方案


如果要将主题应用于特定视图,则必须根据需要在该视图的“主题”或“样式”属性中添加材质样式。

但是,如果您想将主题应用于整个活动,那么您可以通过

setTheme(R.style.AppThemeCustom);

在活动中的 setContentView() 之前添加此行。

在 theme.xml 中定义该主题

<style name="AppThemeCustom" parent="Theme.MaterialComponents.DayNight.DarkActionBar">
    <!-- Primary brand color. -->
    <item name="colorPrimary">@color/purple_500</item>
    <item name="colorPrimaryVariant">@color/purple_700</item>
    <item name="colorOnPrimary">@color/white</item>
    <!-- Secondary brand color. -->
    <item name="colorSecondary">@color/teal_200</item>
    <item name="colorSecondaryVariant">@color/teal_700</item>
    <item name="colorOnSecondary">@color/black</item>
    <!-- Status bar color. -->
    <item name="android:statusBarColor" tools:targetApi="l">?attr/colorPrimaryVariant</item>
    <!-- Customize your theme here. -->
</style>

您说您只想将主题应用于视图。

然后您可以使用主题属性如果您的视图包含多个视图并且您想将主题应用于所有孩子。如果只有一个视图,假设您有一个按钮,那么您可以在该视图中使用样式属性。

注意:您可以在此处使用 2 个选项:预定义主题或您的自定义主题(如我在答案中提到的,在 theme.xml 中自己制作)

您可以在此处找到有关主题和样式的更多信息:


推荐阅读