简体   繁体   English

将 Kotlin 代码翻译成 Java - 理解语法

[英]Translate Kotlin code into Java - Understanding the Syntax

I am looking to try to us this piece of code which thanks to Azimuth reading changes to opposite when user holds the phone upright I need to use this code to experiment in Java however i am unsure of how to translate the code below in to Java:我正在尝试向我们尝试这段代码,这要归功于当用户直立手机时方位角读数会发生变化

    override fun onSensorChanged(event: SensorEvent) {
        if (event.sensor.type != Sensor.TYPE_ROTATION_VECTOR) return
        SensorManager.getRotationMatrixFromVector(rotationMatrix, event.values)
        val (matrixColumn, sense) = when (val rotation = 
                activity.windowManager.defaultDisplay.rotation
        ) {
            Surface.ROTATION_0 -> Pair(0, 1)
            Surface.ROTATION_90 -> Pair(1, -1)
            Surface.ROTATION_180 -> Pair(0, -1)
            Surface.ROTATION_270 -> Pair(1, 1)
            else -> error("Invalid screen rotation value: $rotation")
        }
        val x = sense * rotationMatrix[matrixColumn]
        val y = sense * rotationMatrix[matrixColumn + 3]
        azimuthChanged(-atan2(y, x))
    }

If any one could help understand and translate this to Java that would be a big help, it looks fairly simple but i am unsure on the syntax of these lines:如果有人可以帮助理解并将其翻译为 Java 这将是一个很大的帮助,它看起来相当简单,但我不确定这些行的语法:

val (matrixColumn, sense) = when (val rotation = 
                activity.windowManager.defaultDisplay.rotation
        ) {
            Surface.ROTATION_0 -> Pair(0, 1)
            Surface.ROTATION_90 -> Pair(1, -1)
            Surface.ROTATION_180 -> Pair(0, -1)
            Surface.ROTATION_270 -> Pair(1, 1)
            else -> error("Invalid screen rotation value: $rotation")
        }

Thanks if you can help.谢谢,如果你能帮忙。

This is using a destructuring declaration, which isn't available in Java, so instead you have to declare two variables and then assign them in a switch statement, which is analogous to a Kotlin when statement.这是使用解构声明,这在 Java 中不可用,因此您必须声明两个变量,然后在switch语句中分配它们,这类似于 Kotlin when语句。

int matrixColumn;
int sense;
switch(getActivity().getWindowManager().getDefaultDisplay.getRotation()) {
    case Surface.ROTATION_0:
        matrixColumn = 0;
        sense = 1;
        break;
    case Surface.ROTATION_90:
        matrixColumn = 1;
        sense = -1;
        break;
    case Surface.ROTATION_180:
        matrixColumn = 0;
        sense = -1;
        break;
    default: // Surface.ROTATION_270:
        matrixColumn = 1;
        sense = 1;
        break;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM