屏幕适配方案
场景
App 需要在手机、折叠屏、平板等不同屏幕尺寸上正确显示。
方案
1. 适配层级
| 层级 | 方案 |
|---|---|
| 尺寸单位 | dp + sp,避免 px |
| 布局 | ConstraintLayout 百分比约束 |
| 不同屏幕 | 资源限定符 sw600dp、land |
| 折叠屏 | WindowSizeClass + 自适应布局 |
| 密度 | 提供 xxhdpi、xxxhdpi 图片或矢量图 |
2. WindowSizeClass(Jetpack)
// 根据窗口宽度分三档
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val windowSizeClass = calculateWindowSizeClass(this)
when (windowSizeClass.widthSizeClass) {
WindowWidthSizeClass.Compact -> PhoneLayout() // 手机
WindowWidthSizeClass.Medium -> TabletLayout() // 折叠屏展开 / 小平板
WindowWidthSizeClass.Expanded -> DesktopLayout() // 大平板
}
}
}
}
3. 折叠屏适配
// 监听折叠状态变化
lifecycleScope.launch {
WindowInfoTracker.getOrCreate(this@MainActivity)
.windowLayoutInfo(this@MainActivity)
.collect { layoutInfo ->
val foldFeature = layoutInfo.displayFeatures
.filterIsInstance<FoldingFeature>()
.firstOrNull()
if (foldFeature != null && foldFeature.state == FoldingFeature.State.HALF_OPENED) {
// 半折叠态:上半屏显示内容,下半屏显示控制面板
enableTableTopMode()
}
}
}
4. 常见问题
| 问题 | 解决 |
|---|---|
| 横屏 Activity 重建 | configChanges="orientation|screenSize" 或 ViewModel 保存状态 |
| 折叠屏展开页面异常 | 测试 resizeableActivity="true" |
| NavigationBar 遮挡 | WindowInsetsCompat 处理 |
| 刘海屏/挖孔屏 | DisplayCutout API |
面试答题要点
- dp/sp 是基础,ConstraintLayout 解决比例关系
WindowSizeClass是 Jetpack 推荐的自适应方案- 折叠屏要处理
FoldingFeature状态 - Edge-to-Edge + WindowInsets 是 Android 15+ 的趋势