Setting Android Theme To Follow System Does Not Change To Current System Theme
Solution 1:
Do you change your theme to extend from one of the DayNight
variants, and then call one method to enable the feature ?
For example:
<stylename="MyTheme"parent="Theme.AppCompat.DayNight">
.......
</style>
If you’re using Material Design Components
(and I recommend you to do so), then you can also use the Theme.MaterialComponents.DayNight
theme from their v1.1.0 release.
And you should know the two methods.
The method is static so you can call it at any time. The value you set is not persisted across process starts though, therefore you need to set it every time your app process is started. I recommend setting it in your application class (if you have one)
like so:
[Application]
classMyApplication:Application
{
publicMyApplication(IntPtr handle, JniHandleOwnership ownerShip) : base(handle, ownerShip)
{
}
publicoverridevoidOnCreate()
{
base.OnCreate();
AppCompatDelegate.DefaultNightMode =
AppCompatDelegate.ModeNightFollowSystem;
}
}
Setting DayNight for a single Activity.
You can override the default value in each component with a call to its AppCompatDelegate
’s setLocalNightMode()
. This is handy when you know that only some components should use the DayNight functionality, or for development so that you don’t have to sit and wait for night to fall to test your layout.
Using this method in every Activity is now an anti-pattern, and you should move to using setDefaultNightMode()
instead.
the more you could look here
Update:
I checked the source code and it seems that it miss the handling when the mode is ModeNightFollowSystem
publicvoidsetLocalNightMode(int mode){
switch(mode) {
case-1:
case0:
case1:
case2:
if (this.mLocalNightMode != mode) {
this.mLocalNightMode = mode;
if (this.mApplyDayNightCalled) {
this.applyDayNight();
}
}
break;
default:
Log.i("AppCompatDelegate", "setLocalNightMode() called with an unknown mode");
}
if mLocalNightMode = -1
(ModeNightFollowSystem),and when we call Delegate.SetLocalNightMode(AppCompatDelegate.ModeNightFollowSystem);
(-1) it will go out.
So I find a workaround,get the Current night mode first,then set it directly
case"System Preference":
UiModeManageruiManager= (UiModeManager)GetSystemService(UiModeService);
intmode= (int)uiManager.NightMode;
Delegate.SetLocalNightMode(mode);
prefs.Edit().PutString("theme", "System Preference").Commit();
break;
Post a Comment for "Setting Android Theme To Follow System Does Not Change To Current System Theme"