Search code examples
androidandroid-resources

Is it possible to change configuration ui mode programmatically?


I am developing an Android application that should work on both types of devices: phone, tv and tv box. To do this, I created resources with a TV modifier (for example, textSizes in dimens that will change automatically depending on the uimode), but the problem is that TV boxes use mobile insead of TV. How to change the uimode on app start in order to use dimens with tv modifer?

I've already tried this, but it doesn't work.

config.uiMode = Configuration.UI_MODE_TYPE_TELEVISION
resources.updateConfiguration(config, resources.displayMetrics)

Solution

  • Finally, I've found a solution! Maybe it would be helpful for someone!

    So, I must put it into attachBaseContext instead of onCreate

    override fun attachBaseContext(context: Context?) {
            super.attachBaseContext(context)
    
            if (context != null) {
                SettingsData.initDeviceType(context)
    
                if (SettingsData.deviceType == DeviceType.TV) {
                    resources.configuration.uiMode = uiMode
                    resources.configuration.setTo(resources.configuration)
                }
            }
        }
    

    Also, having switched to another device mode, you have to reload an activity. I've tried finish() StartActivity(intent), but it doesn't work properly. So to fix it up I use ProcessPhoenix lib:

        fun refreshActivity() {
            ProcessPhoenix.triggerRebirth(this)
        }
    

    Warning! If you are using setRequestedOrientation in your MainActivity, it could trigger configuration to change with old uimode.