如何在不使用xml的情况下修改材质组件的主题?

Posted

技术标签:

【中文标题】如何在不使用xml的情况下修改材质组件的主题?【英文标题】:How to modify the theme of material component without using xml? 【发布时间】:2021-10-06 17:03:45 【问题描述】:
<com.google.android.material.button.MaterialButton
    android:layout_
    android:layout_
    android:theme="@style/ThemeOverlay.Life.Red" />

我们可以使用android:theme="***"修改主题。

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

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

很遗憾,没有setTheme方法……

【问题讨论】:

主题只能在View 实例化期间作为整体应用。之后,您要么必须手动修改所有内容,如可用方法允许,要么将View 替换为使用所需主题创建的新实例(您可以使用ContextThemeWrapper,顺便说一句)。 AFAIK,Material Components 没有改变这一点,也没有添加任何帮助它的东西。 【参考方案1】:

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

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

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 中自己制作)

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

【讨论】:

我只想将主题设置为视图。

以上是关于如何在不使用xml的情况下修改材质组件的主题?的主要内容,如果未能解决你的问题,请参考以下文章