android - 如何在不使用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
办法……
解决方案
如果要将主题应用于特定视图,则必须根据需要在该视图的“主题”或“样式”属性中添加材质样式。
但是,如果您想将主题应用于整个活动,那么您可以通过
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 中自己制作)
您可以在此处找到有关主题和样式的更多信息:
推荐阅读
- python - 使用 Python 替换 Pdf 中的图像
- c# - 用我的分叉版本覆盖 NuGet 包中的程序集?
- powershell - Posh 无法识别 LasWriteTime 更改?
- django - DjangoFilterConnectionField 查询所有记录
- php - 如何从数据库中销毁已删除帐户的 COOKIE?
- batch-file - 批处理脚本读取一个列表并为每个分配一个变量
- c++ - 如何修复我为 Arduino 制作的步进电机库?
- c - 无法将 IFUNC 解析器与惰性绑定一起使用
- python - 将 PyQt5 .ui 转换为 .py 显示“类型对象 'QPalette' 没有属性 'PlaceholderText'”
- azure-pipelines - 在可能从模板扩展的 azure 管道 yml 中使用变量吗?