How to adjust text font size to fit textview

后端 未结 22 2263
無奈伤痛
無奈伤痛 2020-11-22 05:15

Is there any way in android to adjust the textsize in a textview to fit the space it occupies?

E.g. I\'m using a TableLayout and adding several Te

22条回答
  •  面向向阳花
    2020-11-22 05:56

    I wrote a short helper class that makes a textview fit within a certain width and adds ellipsize "..." at the end if the minimum textsize cannot be achieved.

    Keep in mind that it only makes the text smaller until it fits or until the minimum text size is reached. To test with large sizes, set the textsize to a large number before calling the help method.

    It takes Pixels, so if you are using values from dimen, you can call it like this:


    float minTextSizePx = getResources().getDimensionPixelSize(R.dimen.min_text_size);
    float maxTextWidthPx = getResources().getDimensionPixelSize(R.dimen.max_text_width);
    WidgetUtils.fitText(textView, text, minTextSizePx, maxTextWidthPx);
    

    This is the class I use:


    public class WidgetUtils {
    
        public static void fitText(TextView textView, String text, float minTextSizePx, float maxWidthPx) {
            textView.setEllipsize(null);
            int size = (int)textView.getTextSize();
            while (true) {
                Rect bounds = new Rect();
                Paint textPaint = textView.getPaint();
                textPaint.getTextBounds(text, 0, text.length(), bounds);
                if(bounds.width() < maxWidthPx){
                    break;
                }
                if (size <= minTextSizePx) {
                    textView.setEllipsize(TextUtils.TruncateAt.END);
                    break;
                }
                size -= 1;
                textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
            }
        }
    }
    

提交回复
热议问题