0

I'm already using setTheme() in onCreate() like:

...
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        data = Utility.GetTheme(this);
        if(data.isDarktheme())
            setTheme(R.style.DarkTheme);
        else
            setTheme(R.style.LightTheme);
        setContentView(R.layout.activity_options);
...

So if I use recreate() in the activity:

switch_theme.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if(isChecked)
                   setTheme(R.style.DarkTheme);
                else
                    setTheme(R.style.LightTheme);
                saveTheme();
                recreate();
            }
        });

My app freezes as I read in another question that it goes into an infinite loop. Is there any way to fix this, preferably with keeping that setTheme() in the beginning of onCreate()?

cheesy
  • 89
  • 1
  • 1
  • 5

1 Answers1

0

You could use AppCompatDelegate.setDefaultNightMode(int) for that you need to use the DayNight theme and on your clickListener you can do AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) or AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)

Here is a link that could help you: Cannot switch between modes in DayNight theme dynamically

Biscuit
  • 4,840
  • 4
  • 26
  • 54
  • Thanks but my custom themes are not really for daylight/evening use, mostly just different colours and i didn't come up with a better name for them. – cheesy Apr 05 '20 at 12:22
  • Oh, then this [post](https://stackoverflow.com/questions/2482848/how-to-change-current-theme-at-runtime-in-android) look at all the answers one might help you – Biscuit Apr 05 '20 at 17:29