简体   繁体   English

多项活动中的暗模式

[英]Dark mode in multiple activities

Is it possible to implement dark mode on multiple activities with a single toggle switch?是否可以使用单个拨动开关在多个活动上实现暗模式? Or it is only possible with the help of fragments.或者只有在片段的帮助下才有可能。

Please bear with me, I am new to Android development and a total beginner.请多多包涵,我是 Android 开发的新手,也是一个初学者。

Yes of course, you can handle dark mode for all the fragments in your app easily like this:是的,当然,您可以像这样轻松地为应用程序中的所有片段处理暗模式:

//for dark mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
// for removing dark mode
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

and if you see there is no change in fragments after changing to dark mode that is because you have defined a color in your fragment and you haven't define a color for dark mode in res>values>colors.如果您在更改为暗模式后看到片段没有变化,那是因为您在片段中定义了一种颜色,并且您没有在 res>values>colors 中为暗模式定义颜色。 for this easily go to res>values>colors and there Right Click> New> values Resource Files > choose a name and in Available Qualifiers choose night mode, now you will have a colors.xml file and a colors.xml(night) file which have colors with same names but different values specific for that mode(Dark/normal) for this easily go to res>values>colors and there Right Click> New> values Resource Files > choose a name and in Available Qualifiers choose night mode, now you will have a colors.xml file and a colors.xml(night) file其中 colors 具有相同的名称但特定于该模式的不同值(暗/正常)

A tricky solution is to use a static boolean variable in any of the class.一个棘手的解决方案是在任何 class 中使用 static boolean 变量。 Initially,最初,

public static boolean darkMode = false;

If the DARK MODE button is pressed, set如果按下DARK MODE按钮,请设置

NameOfTheClass.darkMode = true;

In the onCreate() of all the activities, if darkMode == true then set the background color black.在所有活动的 onCreate() 中,如果darkMode == true则将背景颜色设置为黑色。

You could store the user's preferences and load them when the app is launched.您可以存储用户的偏好并在应用程序启动时加载它们。 For example as a public static boolean and just call in every activity or make a CustomAppCompatActivity class which does the job for you.例如,作为公共 static boolean,只需调用每个活动或进行 CustomAppCompatActivity class 即可为您完成工作。 One way or another.不管怎样。 You've got to be creative.你必须要有创意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM