Auto Scale TextView Text to Fit within Bounds

后端 未结 30 2880
囚心锁ツ
囚心锁ツ 2020-11-21 05:49

I\'m looking for an optimal way to resize wrapping text in a TextView so that it will fit within its getHeight and getWidth bounds. I\'m not simply looking for

30条回答
  •  梦如初夏
    2020-11-21 05:50

    This solutions works for us:

    public class CustomFontButtonTextFit extends CustomFontButton
    {
        private final float DECREMENT_FACTOR = .1f;
    
        public CustomFontButtonTextFit(Context context) {
            super(context);
        }
    
        public CustomFontButtonTextFit(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public CustomFontButtonTextFit(Context context, AttributeSet attrs,
                int defStyle) {
            super(context, attrs, defStyle);
        }
    
        private synchronized void refitText(String text, int textWidth) {
            if (textWidth > 0) 
            {
                float availableWidth = textWidth - this.getPaddingLeft()
                        - this.getPaddingRight();
    
                TextPaint tp = getPaint();
                Rect rect = new Rect();
                tp.getTextBounds(text, 0, text.length(), rect);
                float size = rect.width();
    
                while(size > availableWidth)
                {
                    setTextSize( getTextSize() - DECREMENT_FACTOR );
                    tp = getPaint();
    
                    tp.getTextBounds(text, 0, text.length(), rect);
                    size = rect.width();
                }
            }
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) 
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    
            int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
            int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
    
            refitText(this.getText().toString(), parentWidth);
    
            if(parentWidth < getSuggestedMinimumWidth())
                parentWidth = getSuggestedMinimumWidth();
    
            if(parentHeight < getSuggestedMinimumHeight())
                parentHeight = getSuggestedMinimumHeight();
    
            this.setMeasuredDimension(parentWidth, parentHeight);
        }
    
        @Override
        protected void onTextChanged(final CharSequence text, final int start,
                final int before, final int after) 
        {
            super.onTextChanged(text, start, before, after);
    
            refitText(text.toString(), this.getWidth());
        }
    
        @Override
        protected void onSizeChanged(int w, int h, int oldw, int oldh)
        {
            super.onSizeChanged(w, h, oldw, oldh);
    
            if (w != oldw) 
                refitText(this.getText().toString(), w);
        }
    }
    

提交回复
热议问题