簡體   English   中英

單擊按鈕時如何在我的 android 應用程序中添加暗模式

[英]How to add dark mode in my android app when i click the button

我正在創建一個 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>

並定義這個 styles

 <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()

UPDATE: put this styles in values-v19.xml and values-v21.xml style.xml file

<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"

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM