androidandroid-layoutandroid-windowmanager

Unable to update the day and night modes in android with window manager screens


with WindowManager I am displaying one layout. If I try to change night or day mode it's not effecting. My requirement is if I click on window manager view it should change day mode and vice versa

 AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES)
 var view = layoutInflater.inflate( R.layout.child_layout,null)
 windowManager.addView(view,params)

Solution

  • I had this issue too (with an InputMethodService inflating a keyboard view). I don't know if there's a better way to fix it but this was my workaround:

    I created an explicit day theme and night theme alongside the DayNight theme. I used almost the same attributes in each one, but subclassed different themes (for the default theme my parent was Theme.AppCompat.DayNight.DarkActionBar, so for the other two I used Theme.AppCompat.Light.DarkActionBar for the light theme and Theme.AppCompat for the dark theme). I also translated all the styles in values-night into attributes that could be set by the theme, so that the dark and light modes of my DayNight theme were identical to the other two that I had created.

    I then used a ContextThemeWrapper with a theme according to my theme setting to inflate the view:

    val themeSetting = getStringPref(R.string.themeSettingKey)
    val themeId = if (themeSetting == "MODE_NIGHT_NO") {
        R.style.AppThemeLight
    } else if (themeSetting == "MODE_NIGHT_YES") {
        R.style.AppThemeDark
    } else {  // MODE_NIGHT_FOLLOW_SYSTEM
        R.style.AppTheme
    }
    val wrapper = ContextThemeWrapper(context, themeId)
    LayoutInflater.from(wrapper).inflate(...)
    

    This unfortunately means the theme is only set when the layout is inflated. If the theme setting somehow changes when the view is still open, the theme won't update. (If the setting is MODE_NIGHT_FOLLOW_SYSTEM, it will still dynamically adjust to the system's theme setting).

    Since I'm using an InputMethodService, I added this method to restart the keyboard view whenever it's shown: (this doesn't have a noticeable performance impact per my testing)

    override fun onStartInputView(info: EditorInfo, restarting: Boolean) {
        setInputView(onCreateInputView())
    }
    

    With a WindowManager you'd probably want to restart the window somehow. (As in, destroy the entire window and re-inflate the view). If that's not feasible, I have no idea what to do. I was stuck on this issue for two days.