Usually layout files are stored in the res/layout
folder, layout files for landscape orientation are located in the res/land-layout
folder. How can I add a separate layout file for foldable devices (like Pixel 9 Pro Fold) to the project? Currently, the foldable mode also uses files from res/land-layout
. But I want to make a third design option for such devices.
-> You can use swNNNdp Qualifier (e.g. res/layout-sw600dp)
Foldables (when unfolded) typically have larger screen widths, so you can use:
res/layout-sw600dp/ → for unfolded/foldable screens
res/layout/ → for default (phones)
res/layout-land/ → for landscape
Example:
res/
├── layout/ # Default phone layout (portrait)
├── layout-land/ # Landscape layouts
├── layout-sw600dp/ # For unfolded/foldable screen widths >= 600dp
-> Use Jetpack Window Manager to Detect Fold State
For precise behavior, use Jetpack WindowManager library to detect if device is foldable, and what mode it's in (e.g. half-opened, tabletop, etc.). You can then inflate specific layouts programmatically.
implementation "androidx.window:window:1.3.0"
val windowInfoRepo = WindowInfoTracker.getOrCreate(this)
lifecycleScope.launch {
windowInfoRepo.windowLayoutInfo(this@MainActivity)
.collect { layoutInfo ->
if (layoutInfo.displayFeatures.any { it is FoldingFeature }) {
// Inflate special fold layout
setContentView(R.layout.activity_foldable)
} else {
// Inflate default layout
setContentView(R.layout.activity_main)
}
}
}