androidandroid-layoutandroid-gravity

Android AutoResizeTextView - Vertical Gravity off after resize


I'm using the AutoResizeTextView class found here. Auto Scale TextView Text to Fit within Bounds and it works great. However, I have the textview in a RelativeLayout and I have the layout_centerVertical property on the TextView set to true. Works great, unless the TextView doesn't fit and resizes itself. Then the text is no longer vertically centered within the RelativeLayout.

I'm guessing this is because the vertical alignment is performed BEFORE the TextView does its resizing.

How can I fix this? Is there a way to re-trigger the gravity alignment of the View after the text is resized?

Example layout

<RelativeLayout 
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:padding="10dp">

     <com.mypackage.android.AutoResizeTextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="Some Text Here"
          android:maxLines="1"
          android:ellipsize="end" />

</RelativeLayout>

Solution

  • Try to also trigger resizeText() in

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        // trigger here
    }
    
    //This is called during layout when the size of this view has changed
    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        // trigger here
    }