Android 当屏幕旋转时更改工具栏的宽度

Android 当屏幕旋转时更改工具栏的宽度,android,toolbar,Android,Toolbar,我使用屏幕顶部的工具栏。当用户旋转设备时,我使用设备传感器来监听旋转,并将工具栏旋转到屏幕左侧(我想防止其他视图旋转)。旋转效果很好,但我希望工具栏的宽度在左侧时为屏幕高度。以下代码未按预期工作: fun repositionToolBar(){ val toolBarHeight = toolbar.height val screenWidth = rootLayout.width val screenHeight = rootLayout.he

我使用屏幕顶部的
工具栏
。当用户旋转设备时,我使用设备传感器来监听旋转,并将
工具栏
旋转到屏幕左侧(我想防止其他视图旋转)。旋转效果很好,但我希望
工具栏的宽度在左侧时为屏幕高度。以下代码未按预期工作:

fun repositionToolBar(){
        val toolBarHeight = toolbar.height
        val screenWidth = rootLayout.width
        val screenHeight = rootLayout.height
        toolbar.rotation = 360f - mCurrentRotation.toFloat()

        if(mCurrentRotation==90){
            toolbar.translationX = -screenWidth/2f+toolBarHeight/2f
            toolbar.translationY = screenHeight/2f-toolBarHeight/2f
            toolbar.layoutParams.width = screenHeight //width of the tool bar changed but toolbar was not in left side, it rotated and laid at center of screen
        }
        else if(mCurrentRotation==270){
            toolbar.translationX = screenWidth/2f-toolBarHeight/2f
            toolbar.translationY = screenHeight/2f-toolBarHeight/2f
            toolbar.layoutParams.width = screenHeight //The toolbar disappeared
        }
        else{ //360 or 0 degree
            toolbar.translationX = 0f
            toolbar.translationY = 0f
            toolbar.layoutParams.width = screenWidth //the toolbar is on top as I expect.
        }
    }
以下是XML文件:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:id="@+id/rootView"
    android:layout_height="match_parent">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        app:contentInsetLeft="0dp"
        app:contentInsetStart="0dp"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/rentedInPastColor"
        app:layout_constraintTop_toTopOf="parent">
    </androidx.appcompat.widget.Toolbar>

</androidx.constraintlayout.widget.ConstraintLayout>

你能指出上面有什么错误吗。谢谢你的关注