使用getDisplay和getRotation检测屏幕方向时TextView无法正常显示
Android 屏幕方向检测不生效问题修复方案
现存问题梳理
- 工具方法逻辑错误:自定义的
getRotation()方法固定返回0,无法获取设备实时旋转状态 - API使用混淆:
DisplayManager.getDisplay()的入参是显示设备ID(默认主屏幕ID为Display.DEFAULT_DISPLAY),不是旋转角度值,API调用逻辑完全错误 - 判断逻辑错误:when表达式错误使用
Display对象作为匹配条件,应该直接匹配旋转值 - 控件ID不匹配:XML布局中方向值控件ID为
orientationText,代码中调用的orientationView不存在,赋值操作无效 - 缺少状态监听:仅在
onCreate中执行一次检测,屏幕旋转后不会自动更新状态 - 布局约束异常:两个TextView的约束依赖不存在的
rollLabel、rollText控件,会导致控件不可见
修正后的代码实现
1. 旋转值获取方法(官方兼容写法)
private fun getCurrentRotation(): Int { return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { display?.rotation ?: Surface.ROTATION_0 } else { @Suppress("DEPRECATION") windowManager.defaultDisplay.rotation } }
2. 方向判断与控件赋值逻辑
// 先绑定正确的控件 lateinit var orientationText: TextView override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // 绑定控件 orientationText = findViewById(R.id.orientationText) // 初始化先获取一次方向 updateOrientationText() } private fun updateOrientationText() { val rotation = getCurrentRotation() val orientationStr = when (rotation) { Surface.ROTATION_0 -> "竖屏" Surface.ROTATION_90 -> "横屏(顺时针90度)" Surface.ROTATION_180 -> "反向竖屏" Surface.ROTATION_270 -> "横屏(逆时针90度)" else -> "未知状态" } orientationText.text = orientationStr }
3. 注册屏幕旋转监听实现实时更新
在onCreate中添加监听逻辑,页面销毁时注销监听避免内存泄漏:
lateinit var displayListener: DisplayManager.DisplayListener lateinit var displayManager: DisplayManager override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) orientationText = findViewById(R.id.orientationText) // 初始化监听 displayManager = getSystemService(Context.DISPLAY_SERVICE) as DisplayManager displayListener = object : DisplayManager.DisplayListener { override fun onDisplayAdded(displayId: Int) = Unit override fun onDisplayRemoved(displayId: Int) = Unit override fun onDisplayChanged(displayId: Int) { if (displayId == Display.DEFAULT_DISPLAY) { updateOrientationText() } } } displayManager.registerDisplayListener(displayListener, null) updateOrientationText() } override fun onDestroy() { super.onDestroy() displayManager.unregisterDisplayListener(displayListener) }
4. 修正布局约束
<TextView android:id="@+id/orientationLabel" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/orientation" android:textColor="@color/red" android:layout_marginStart="15dp" android:layout_marginTop="15dp" app:layout_constraintTop_toTopOf="parent" app:layout_constraintStart_toStartOf="parent" /> <TextView android:id="@+id/orientationText" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/orientation_goes_here" android:textColor="@color/red" android:layout_marginStart="4dp" app:layout_constraintTop_toTopOf="@id/orientationLabel" app:layout_constraintStart_toEndOf="@id/orientationLabel"/>
内容的提问来源于stack exchange,提问作者Georgi Tasev
相关产品推荐
相关产品推荐

