How to manage different layout on Configuration Changed in activity for foldable android device?

1k views Asked by At

Created a demo for foldable devices. When the device is folded, I want to show one layout and when the device is unfolded I have different layout to show.then how to manage two layout according to Configuration Changed.?

override fun onConfigurationChanged(newConfig: Configuration) {
        super.onConfigurationChanged(newConfig)
        Log.i(myTag, "onConfigurationChanged...")
}
3

There are 3 answers

1
user3471194 On

You can set callbacks to receive states: CLOSED, HALF, OPEN.

private fun setFoldableCallbacks() {
        mainThreadExecutor = ContextCompat.getMainExecutor(this)
        windowManager = WindowManager(this, null)
        windowManager.registerDeviceStateChangeCallback(
            mainThreadExecutor,
            deviceStateChangeCallback
        )
        Handler(Looper.getMainLooper()).postDelayed({
            windowManager.registerLayoutChangeCallback(mainThreadExecutor, layoutChangeCallback)
        }, 1000)
    }
0
Javier Marsicano On

Instead of implementing onConfigurationChanged method you should use Jetpack WindowManager as explained by @user3471194. But keep in mind that its API has changed quite a bit, so with version 1.0.0-alpha05 WindowManager's constructor might have only one parameter (activity). Also I recommend to declare activity's configChanges in Manifest file as follows

<activity
        ...
        android:configChanges="screenLayout|screenSize|orientation|smallestScreenSize">
        ...
</activity>

On the other hand, the callback you pass to registerLayoutChangeCallback method no longer retrieves a DeviceState object but a WindowLayoutInfo instead, which has FoldingFeature that might be set as STATE_FLAT, STATE_FLIPPED,STATE_HALF_OPENED etc or it will be null if the device is non-foldable.

1
Anand Pandey On
  if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
          setcontentview();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
            setcontentview();
}

See if that works for you.