【问题标题】:How to add dark mode in my android app when i click the button单击按钮时如何在我的Android应用程序中添加暗模式
【发布时间】:2020-04-25 15:17:25
【问题描述】:

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

非常感谢大家。

【问题讨论】:

    标签: java android


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      • 2018-05-16
      • 1970-01-01
      • 2017-03-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多