java - 单击按钮时如何在我的android应用程序中添加暗模式
问题描述
我正在创建一个 Android 应用程序,但我不知道如何将我的应用程序转换为夜间模式,我希望当我单击按钮时它会切换到夜间模式,当我再次按下它时它将恢复正常
非常感谢大家。
解决方案
首先在 style.xml 中创建 2 个不同名称的样式
<style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">#fff</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="PrimaryTextColor">#fff</item>
</style>
<style name="AppThemeDark" parent="Theme.MaterialComponents.NoActionBar">
<item name="colorPrimary">#2196F3</item>
<item name="colorPrimaryDark">#303030</item>
<item name="colorAccent">#03A9F4</item>
<item name="PrimaryTextColor">#03A9F4</item>
</style>
并定义这种风格
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
<style name="AppThemeDark.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
<style name="Light" parent="AppTheme.NoActionBar"/>
<style name="Dark" parent="AppThemeDark.NoActionBar"/>
在 values 文件夹中创建一个 attrs.xml 文件,您应该在此处定义颜色键
<?xml version="1.0" encoding="utf-8"?>
<resources>
<attr name="PrimaryTextColor" format="color"/>
<attr name="SecondaryTextColor" format="color"/>
</resources>
现在在 layout.xml 你应该这样设置颜色:
android:background="?attr/PrimaryTextColor"
最后是为了改变黑暗的主题
setTheme(R.style.Dark)
recreate()
对于光
setTheme(R.style.Light)
recreate()
更新:将此样式放入 values-v19.xml 和 values-v21.xml style.xml 文件中
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowTranslucentStatus">false</item>
</style>
<style name="AppThemeDark.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowTranslucentStatus">false</item>
</style>
并且您在 AndroidManifest.xml 中的主题必须是:
android:theme="@style/AppTheme.NoActionBar"
推荐阅读
- azure-resource-manager - 将价值从一个步骤传递到 ARM 部署的下一步
- mysql - 如何使用 Laravel 查询构建器构建这样的查询?
- google-api - 从 Google Calendar API 获取澳大利亚的假期列表
- javascript - 导入 HTML 元素的更好方法?
- mysql - 如何找到购买相同产品的用户对?
- python - 如何在 booking.com 上使用 scrapy 而不会被阻止?
- docker - 如何使用filebeat或logstash,fluentd读取pod内kubernetes中的stdout stderr日志
- swift - 如何显示特定数据,并在 Firestore 中将其组合在一起
- javascript - js 代码适用于 firefox,但不适用于 chrome opera 和 edge
- java - Java打印双科学记数法,少位数