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

时间:2020-09-16 06:57:29

标签: android toolbar

我在屏幕上方使用了Toolbar。当用户旋转设备时,我使用设备传感器来监听旋转并将Toolbar旋转到屏幕的左侧(我想防止其他视图旋转)。旋转效果很好,但是我希望Toolbar的宽度在屏幕左侧时为屏幕高度。以下代码无法正常工作:

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>

您能指出上述错误吗?感谢您的关注。

0 个答案:

没有答案