首页 > 解决方案 > 单击按钮时如何在我的android应用程序中添加暗模式

问题描述

我正在创建一个 Android 应用程序,但我不知道如何将我的应用程序转换为夜间模式,我希望当我单击按钮时它会切换到夜间模式,当我再次按下它时它将恢复正常

非常感谢大家。

标签: javaandroid

解决方案


首先在 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"

推荐阅读