Reputation: 401
I searched around for a while and had to "learn it the hard way":
FragmentActivity from androidx.fragment.app.FragmentActivity does NOT work together with the documented way to change themes.
So for example:
You switch from day-theme to night-theme via AppCompatDelegate.setDefaultNightMode()
in the onCreate()
of you App class (a class which extends the Application
class) because the configuration is not persistent after closing/opening the app and to make sure the configuration change (which is triggered by setDefaultNightMode()
) is done before any activities are created. So far so good: I.E. An AppCompatActivity
will be created using the preferred theme. BUT if you launch a FragmentActivity
this activity will not use the resources provided for night mode.
I used
void checkNightModeConfiguration() {
int currentNightMode = getResources().getConfiguration().uiMode
& Configuration.UI_MODE_NIGHT_MASK;
switch (currentNightMode) {
case Configuration.UI_MODE_NIGHT_NO:
Log.i(TAG, "night mode flag NOT set");
break;
case Configuration.UI_MODE_NIGHT_YES:
Log.i(TAG, "night mode flag set");
break;
case Configuration.UI_MODE_NIGHT_UNDEFINED:
Log.i(TAG, "night mode flag unknown");
break;
}
}
to check when the activity reads out the configuration. For AppCompatActivity this already happened in the beginning of onCreate(). For FragmentActivity this happens a while later (maybe someone could clarify at which point this happens?), definitely after the layout is infalted and therefore the layout is never inflated with the night resources.
For me the easiest solution was to use AppCompatActivity instead because I do not need the backwards compatibility for nested fragments and do not support API Level < 17 (see this post).
Hope this safes time for some of you out there.
Sources
DayNight — Adding a dark theme to your app
Activity, AppCompatActivity, FragmentActivity, and ActionBarActivity: When to Use Which?
Developing Themes with Style (Android Dev Summit '19)
Upvotes: 0
Views: 1494
Reputation: 200120
FragmentActivity
, being part of the Fragment library and having no dependency on AppCompat (in fact, AppCompat depends on Fragment) is totally unaware of AppCompatDelegate
and any night mode you set on that object.
You should always use AppCompatActivity
if you want your activity to be aware of AppCompatDelegate
and any of the night mode fixes that are specific to AppCompat
.
Upvotes: 2