![](/img/trans.png)
[英]How to change the language in LocaleManager without recreating the activity?
[英]How to detect screen rotation without rotating/recreating the activity?
我希望能夠檢測手機是處於橫向模式還是縱向模式,但我不希望我的活動和所有按鈕一起旋轉。
此代碼檢測旋轉,但它也旋轉屏幕:
Display display = getWindowManager().getDefaultDisplay();
int rotation = display.getRotation();
rotVal.setText("Rotation: " + rotation);
我試圖在 MainActivity 中使用此功能將活動鎖定為縱向模式,但rotation
值不會改變。 (我想是有道理的)
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
我還在清單文件中嘗試了android:screenOrientation="portrait"
但rotVal
保持為零。
這個答案有一個旋轉動畫,我不想要那個。 我希望屏幕即使在橫向模式下也能保持原樣,沒有旋轉,沒有動畫等。
這個答案不起作用。 當我旋轉手機時, rotVal
保持為零。
有沒有辦法在不旋轉/重新創建布局的情況下檢測方向?
您鏈接到的第二個 Stack Overflow答案將起作用,但您不能像您那樣查詢方向。
首先,將應用程序鎖定為縱向模式。 以下代碼應該可以工作,但不包括所有動畫代碼。
private lateinit var orientationListener: OrientationListener
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Code here to do Activity-related stuff.
// Set up a listener to detect orientation changes.
orientationListener = OrientationListener(this)
}
override fun onStart() {
orientationListener.enable()
super.onStart()
}
override fun onStop() {
orientationListener.disable()
super.onStop()
}
private class OrientationListener(context: Context?) : OrientationEventListener(context) {
val ROTATION_O = 1 // portrait
val ROTATION_90 = 2 // landscape counter-clockwise
val ROTATION_180 = 3 // portrait inverted
val ROTATION_270 = 4 // landscape clockwise
private var rotation = 0
override fun onOrientationChanged(orientation: Int) {
if ((orientation < 35 || orientation > 325) && rotation != ROTATION_O) { // PORTRAIT
rotation = ROTATION_O
} else if (orientation > 145 && orientation < 215 && rotation != ROTATION_180) { // REVERSE PORTRAIT
rotation = ROTATION_180
} else if (orientation > 55 && orientation < 125 && rotation != ROTATION_270) { // REVERSE LANDSCAPE
rotation = ROTATION_270
} else if (orientation > 235 && orientation < 305 && rotation != ROTATION_90) { //LANDSCAPE
rotation = ROTATION_90
}
// We'll just display the value, but it should be stashed for further use or acted upon immediately.
Log.d("Applog", "rotation = $rotation")
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.