2

I am setting the night mode in onCreate of an activity. So every single activity in the app turns to night mode and all the previous activities gets recreated. But I need only that particular activity to be in night mode and all other activities to be in light mode. How to achieve this ? Below line of code I am using in oncreate of an activity to set to night mode.

AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)

a_local_nobody
  • 7,947
  • 5
  • 29
  • 51
Rajeev Shetty
  • 1,534
  • 1
  • 17
  • 27
  • why not just turn it off in every other activity ? – a_local_nobody Feb 11 '21 at 06:18
  • @a_local_nobody You mean to set AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO) in every other activity? – Rajeev Shetty Feb 11 '21 at 06:20
  • yes, i don't think there's another way of doing it, you could consider making a base class or something to make this easier – a_local_nobody Feb 11 '21 at 06:21
  • calling `setDefaultNightMode` with opposite mode than currently set makes all `Activities` on stack recreate, thats very inefficient and may lead to losing some data (e.g. scroll position or texts in `EditText`s, depends on saving instance state implementation) – snachmsm Feb 11 '21 at 07:10

3 Answers3

4

Try This to Set Modes Only for Single Activity


Light Mode

getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_NO);

Dark Mode

getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_YES);

System Default

getDelegate().setLocalNightMode(AppCompatDelegate.MODE_NIGHT_FOLLOW_SYSTEM);
anonymous
  • 81
  • 3
0

sadly you don't have option for switching only one Activity into dark mode leaving all others in light. setDefaultNightMode is one and only method and it is working for whole Application and all Activities running in it.

you have to make two separated styles/themes for this one Activity and switch its theme programmatically (here you find out how) or if this one Activity is always dark then set its theme straight inside manifest

snachmsm
  • 17,866
  • 3
  • 32
  • 74
0

you can change the theme of the activity in the manifest file

Muhammad Asad
  • 694
  • 6
  • 10