Day/Night mode changes from fragment starts from the first fragment

788 Views Asked by At

I faced a problem at the time of day/night mode change from fragment that without recreate the parent activity the mode not change but I want to change the mode from fragment without move from the current fragment.

public void setNightMode(Context target, boolean state){

    //UiModeManager uiManager = (UiModeManager) target.getSystemService(Context.UI_MODE_SERVICE);
    UiModeManager uiManager = (UiModeManager) getActivity().getSystemService(Context.UI_MODE_SERVICE);

    if (state) {
        //setTheme(R.style.DarkTheme);
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            //setting up Night Mode...
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES);

        } else {
            uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
        }
        //uiManager.setNightMode(UiModeManager.MODE_NIGHT_YES);
        night_mode = false;
        //homeBinding.toolbar.setHeaderColour(HomeActivity.this, false);
    } else {
        if (android.os.Build.VERSION.SDK_INT > Build.VERSION_CODES.M){
            AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO);

        } else {
            uiManager.setNightMode(UiModeManager.MODE_NIGHT_NO);
        }
        night_mode = true;
    }
}
1

There are 1 best solutions below

5
Mobin Yardim On

for change to night mode :

delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_YES

and change to the light mode:

delegate.localNightMode = AppCompatDelegate.MODE_NIGHT_NO

also for use this feature you must implement the androidX appcompat library

implementation 'androidx.appcompat:appcompat:1.4.0'