我想在设备方向改变时获取屏幕高度和宽度,并且我使用 OrientationEventListener 而不是 onConfigurationChanged() 方法。
对于以下代码:
1)方向事件监听器
mOrientationListener = object : OrientationEventListener (context, SensorManager.SENSOR_DELAY_UI)
{
override fun onOrientationChanged (orientation: Int)
{
if (gTemp == false) {
gTemp = true
} else if (orientation == 0 || orientation == 180) {
Log.d ("orientation", "Orientation: Portrait")
width = TWOSScreenAspectsAndroid.GetScreenHeight ()
height = TWOSScreenAspectsAndroid.GetScreenWidth ()
// call cpp function
OrientationChanged (pInstructionSetIndex, width, height)
} else if (orientation == 90 || orientation == 270) {
Log.d ("orientation", "Orientation: LandScape")
width = TWOSScreenAspectsAndroid.GetScreenHeight ()
height = TWOSScreenAspectsAndroid.GetScreenWidth ()
// call cpp function
OrientationChanged (pInstructionSetIndex, width, height)
}
}
}
if (mOrientationListener.canDetectOrientation ()) {
mOrientationListener.enable ()
}
2)TWOSScreenAspectsAndroid.GetScreenHeight()
@JvmStatic
public fun GetScreenHeight (): Int
{
val metric: WindowMetrics
val insets: Insets // An Insets instance holds four integer offsets which describe changes to the four edges of a Rectangle.
val displayMetrics: DisplayMetrics
val height: Int
val insetsHeight: Int
val context: Context?
val activity: Activity
context = TWProcessStates.GetMainActivityContext ()
activity = context as Activity
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Code for API level 30 and higher
metric = activity.windowManager.currentWindowMetrics
insets = activity.windowManager.currentWindowMetrics.windowInsets.getInsetsIgnoringVisibility (WindowInsets.Type.navigationBars() or WindowInsets.Type.displayCutout ())
insetsHeight = insets.top + insets.bottom
Log.d ("orientation_height", "${insets.right}, ${insets.left}, ${insets.top}, ${insets.bottom}")
height = metric.bounds.height () - insetsHeight
} else {
// Code for API level 29 and lower
displayMetrics = DisplayMetrics ()
activity.windowManager.defaultDisplay.getMetrics (displayMetrics)
height = displayMetrics.heightPixels
}
Log.d ("orientation_height", "Inside TWOSScreenAspectsAndroid::GetScreenHeight Height: $height")
return height
}
当方向为横向时,我得到纵向模式的高度和宽度,反之亦然,如下面的日志所示:
如何解决这个问题?
您错误地将宽度分配给高度函数。你写了这个:
width = TWOSScreenAspectsAndroid.GetScreenHeight ()
应该是:
height = TWOSScreenAspectsAndroid.GetScreenHeight ()
反之亦然