[JAVA] [Beginner's memorandum] Story when rotating TextView and Button with text

When you want to draw text that is rotated 90 degrees vertically, you should think about writing this using rotation for the time being.

rotation_bad.xml


<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/sampleTextView"
    android:text="@string/sampleText"
    android:rotation="90"
    android:gravity="center" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/sampleButton"
    android:text="@string/sampleText"
    android:rotation="90"
    android:gravity="center" />

As soon as I run it, I know it, but it doesn't work as expected. After defining the size of View with layout_width and layout_height, rotation is only executed for the text inside. There was something like inheriting the class for vertical writing and recreating it, but for the time being, this is one of the simple solutions.

You can use ConstraintLayout to bring the TextView to a good position.

rotation_good.xml


<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Space
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/textSpace" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        app:layout_constraintDimensionRatio="1:1"
        android:id="@+id/sampleTextView"
        android:text="@string/sampleText"
        android:rotation="90"
        android:gravity="center"
        app:layout_constraintTop_toTopOf="@+id/textSpace"
        app:layout_constraintBottom_toBottomOf="@+id/textSpace"
        app:layout_constraintStart_toStartOf="@+id/textSpace"
        app:layout_constraintEnd_toEndOf="@+id/textSpace"
        android:translationZ="10dp" />

</android.support.constraint.ConstraintLayout>

After securing only the space in the view placed below, ignore it and cover it with a new TextView from above. The point is that if it is a square view, there is no problem even if it is rotated, and if it is centered, this will work. It is possible to shift the position of the TextView that covers left and right alignment, and the same can be done with the button if the Space part is a Button. The reason why translationZ is set to a positive value is that depending on the type of View placed below, the TextView will be covered and the text will not be displayed.

It would be easier to create a class and implement a rotated TextView, so let's think about it when we have time.

Recommended Posts

[Beginner's memorandum] Story when rotating TextView and Button with text
Change the layout when rotating with onConfigurationChanged