You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jetpack Compose 获取屏幕宽高的方法,除getWindowManager外还有哪些途径?

Jetpack Compose 中获取屏幕尺寸的替代实现方案

你提到的 getWindowManager().getDefaultDisplay() 方法在API 30及以上版本已被官方废弃,以下方案均兼容新老系统版本,无需处理废弃API适配问题。

下面分场景给出具体实现:

1. 官方推荐响应式适配方案:WindowSizeClass

适用于做不同屏幕尺寸的布局适配,不需要硬编码像素值,自动跟随窗口尺寸变化更新:

  • 先引入依赖(使用Material3的项目默认已包含):
    implementation "androidx.compose.material3:material3-window-size-class:1.2.1"
    
  • Activity中调用示例:
    class MyActivity : ComponentActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContent {
                val windowSizeClass = rememberWindowSizeClass()
                // 宽度分类:COMPACT(<=600dp, 手机竖屏)、MEDIUM(600~839dp, 平板竖屏/折叠屏内屏)、EXPANDED(>=840dp, 平板横屏)
                val widthSizeClass = windowSizeClass.widthSizeClass
                // 高度分类逻辑和宽度一致
                val heightSizeClass = windowSizeClass.heightSizeClass
                
                // 可以根据分类直接加载不同布局
                when(widthSizeClass) {
                    WindowWidthSizeClass.Compact -> PhonePortraitLayout()
                    WindowWidthSizeClass.Medium -> TabletPortraitLayout()
                    WindowWidthSizeClass.Expanded -> TabletLandscapeLayout()
                }
            }
        }
    }
    

2. 获取当前应用窗口的精确尺寸

如果需要拿到具体的dp/px数值,直接使用Compose提供的 CompositionLocal 即可:

@Composable
fun getWindowSize(): Pair<Dp, Float> {
    val config = LocalConfiguration.current
    val density = LocalDensity.current
    
    // 窗口可用宽度,单位dp,自动排除系统栏占用
    val windowWidthDp = config.screenWidthDp.dp
    // 转成像素值
    val windowWidthPx = with(density) { windowWidthDp.toPx() }
    
    // 高度的获取逻辑和宽度完全一致
    val windowHeightDp = config.screenHeightDp.dp
    val windowHeightPx = with(density) { windowHeightDp.toPx() }
    
    return windowWidthDp to windowWidthPx
}

3. 获取包含系统栏的完整物理屏幕尺寸

如果需要拿到包含状态栏、导航栏在内的整块屏幕的物理尺寸,可以搭配WindowInsets计算:

@Composable
fun getFullPhysicalScreenSize(): Pair<Float, Float> {
    val config = LocalConfiguration.current
    val density = LocalDensity.current
    val insets = LocalWindowInsets.current.systemBars
    
    val fullWidthPx = with(density) {
        config.screenWidthDp.dp.toPx() + insets.left.toPx() + insets.right.toPx()
    }
    val fullHeightPx = with(density) {
        config.screenHeightDp.dp.toPx() + insets.top.toPx() + insets.bottom.toPx()
    }
    
    return fullWidthPx to fullHeightPx
}

内容的提问来源于stack exchange,提问作者AbdulMomen عبدالمؤمن

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 05:27:01