跳到主要内容

屏幕适配方案

场景

App 需要在手机、折叠屏、平板等不同屏幕尺寸上正确显示。

方案

1. 适配层级

层级方案
尺寸单位dp + sp,避免 px
布局ConstraintLayout 百分比约束
不同屏幕资源限定符 sw600dpland
折叠屏WindowSizeClass + 自适应布局
密度提供 xxhdpixxxhdpi 图片或矢量图

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

面试答题要点

  1. dp/sp 是基础,ConstraintLayout 解决比例关系
  2. WindowSizeClass 是 Jetpack 推荐的自适应方案
  3. 折叠屏要处理 FoldingFeature 状态
  4. Edge-to-Edge + WindowInsets 是 Android 15+ 的趋势

相关链接