Android Studio模拟器折叠屏姿态检测配置问题求助
折叠屏模拟器配置与姿态检测问题
我正在使用Jetpack WindowManager库的WindowLayoutInfo类获取折叠屏设备的姿态信息(如flat、half_opened等),开发时参考了自适应UI官方教程及《Large Screens & Foldables Tutorial for Android》教程。
在Android Studio最新稳定版中,我创建了支持可调整大小的模拟器实例(实验特性),但测试应用时,折叠屏状态始终显示默认的NormalPosture。单元测试正常,但UI测试无法检测到折叠状态,现寻求正确的模拟器配置方案。
核心代码实现
sealed interface DevicePosture { object NormalPosture : DevicePosture data class BookPosture( val hingePosition: Rect ) : DevicePosture data class Separating( val hingePosition: Rect, var orientation: FoldingFeature.Orientation ) : DevicePosture } @OptIn(ExperimentalContracts::class) fun isBookPosture(foldFeature: FoldingFeature?): Boolean { contract { returns(true) implies (foldFeature != null) } return foldFeature?.state == FoldingFeature.State.HALF_OPENED && foldFeature.orientation == FoldingFeature.Orientation.VERTICAL } @OptIn(ExperimentalContracts::class) fun isSeparating(foldFeature: FoldingFeature?): Boolean { contract { returns(true) implies (foldFeature != null) } return foldFeature?.state == FoldingFeature.State.FLAT && foldFeature.isSeparating } /* ... */ val devicePostureFlow = WindowInfoTracker.getOrCreate(this).windowLayoutInfo(this) .flowWithLifecycle(this.lifecycle) .map { layoutInfo -> val foldingFeature = layoutInfo.displayFeatures.filterIsInstance<FoldingFeature>().firstOrNull() when { isBookPosture(foldingFeature) -> DevicePosture.BookPosture(foldingFeature.bounds) isSeparating(foldingFeature) -> DevicePosture.Separating(foldingFeature.bounds, foldingFeature.orientation) else -> DevicePosture.NormalPosture } } .stateIn( scope = lifecycleScope, started = SharingStarted.Eagerly, initialValue = DevicePosture.NormalPosture )
模拟器配置解决方案
1. 创建合规的折叠屏模拟器
- 打开AVD Manager,点击「Create Virtual Device」
- 直接选择官方提供的折叠屏设备(如Pixel Fold);若需自定义,选择「New Hardware Profile」:
- 设置屏幕参数:例如内屏2208x1840、外屏2208x1080,尺寸7.6英寸(折叠后5.8英寸)
- 勾选「Foldable」选项,配置铰链位置(垂直折叠时设为屏幕中间)
- 选择Android 12L及以上版本的系统镜像(WindowManager对折叠屏的完善支持从该版本开始)
2. 启用实验特性并配置折叠状态
- 进入Android Studio设置:
File > Settings > Experimental,勾选「Resizable Emulator」 - 启动模拟器后,打开右侧边栏的「Extended controls」,找到「Foldable」选项卡:
- 切换到Half-opened状态:设置角度为90度,对应代码中的
BookPosture - 切换到Flat状态:设置角度为180度,若需触发
Separating状态,需在硬件配置中勾选「Is separating」
- 切换到Half-opened状态:设置角度为90度,对应代码中的
- 重启模拟器确保配置生效
3. 测试阶段的额外配置
- 确认依赖版本:在
build.gradle中添加最新版WindowManager依赖:implementation "androidx.window:window:1.1.0" implementation "androidx.window:window-java:1.1.0" - UI测试中,可通过
WindowLayoutInfoTestUtil模拟折叠状态:@Test fun testBookPosture() { val foldingFeature = FoldingFeature( bounds = Rect(0, 920, 2208, 921), state = FoldingFeature.State.HALF_OPENED, orientation = FoldingFeature.Orientation.VERTICAL, isSeparating = false ) val windowLayoutInfo = WindowLayoutInfo(listOf(foldingFeature)) WindowInfoTrackerTestUtil.setWindowLayoutInfo(context, windowLayoutInfo) // 此处编写UI响应验证逻辑 }
内容的提问来源于stack exchange,提问作者Marlon López
相关产品推荐
相关产品推荐

