This is a TextView.
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:parentTag="androidx.constraintlayout.widget.ConstraintLayout">
<FrameLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="@dimen/high_padding"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
android:id="@+id/draggable_view_component_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</FrameLayout>
...
</merge>
As you can see Im coding some kind of customizable TextView. But when I execute this:textView.setRotation(45)
, I get this annoying result (image below). As it appears, the textview is not updating its width or height when rotated (I logged getWidth() and getHeight() inside onMeasure()).
I already found these questions:
But the answers only fix size when orientation is exactly 90 degrees (they just swap width and height)
So, is there a way to make the width and height dynamically fit the textView when rotated?
Thanks in advance !
EDIT
Based on @avalerio 's answer, I found out how to calculate the width and height...
public class CustomEditText extends androidx.appcompat.widget.AppCompatEditText {
...
@Override
public void setRotation(float rotation) {
super.setRotation(rotation);
requestLayout();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int oldwidth = getMeasuredWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
int oldheight = getMeasuredHeight() - getCompoundPaddingTop() - getCompoundPaddingBottom();
int width = oldwidth;
int height = oldheight;
double angle = Math.toRadians(getRotation());
...
// a bunch of boring calculations
...
width += getCompoundPaddingLeft() + getCompoundPaddingRight();
height += getCompoundPaddingTop() + getCompoundPaddingBottom();
setMeasuredDimension(width, height);
}
The height and width seem correct, but the textView is still limited to its original bounds. Logging getHeight() and getMeasuredHeight() give the correct values, but how can I make textView draw in the new bounds ?