0

Part of my app displays a single 5-character word in a TextView which should fill the entire screen. The questions listed below address this same issue:

How to adjust text font size to fit textview

Have TextView scale its font size to fill parent?

Text size and different android screen sizes

Auto-fit TextView for Android

However, since my case requires only one 5-character word to fill the entire screen, is there a simpler way to do this? If not, would it be practical to simply provide drawable resources (assuming that the 5-character word will always be the same)?

Thanks!

Community
  • 1
  • 1
pez
  • 3,859
  • 12
  • 40
  • 72

1 Answers1

1

I'm going to give you some code which shows the exact opposite of what you requested. The code below shrinks a line of text until it fits within the desired area. But there is the basic idea: Get the paint of the textView and then measure it. Adjust the size and remeasure it e.g. textView.getPaint().measureText("Your text")

public static float calculateTextSizeToFit(TextView textView, String desiredText, int limitSpSize, float desiredTxtPxSize) {
    Paint measurePaint = new Paint(textView.getPaint());
    measurePaint.setTextSize(desiredTxtPxSize);
    float pWidth = measurePaint.measureText(desiredText);
    float labelWidth = textView.getWidth();
    int maxLines = textView.getMaxLines();

    while (labelWidth > 0 && pWidth/maxLines > labelWidth-20) {
        float textSize = measurePaint.getTextSize();
        measurePaint.setTextSize(textSize-1);
        pWidth = measurePaint.measureText(desiredText);
        if (textSize < TypedValue.applyDimension(
                TypedValue.COMPLEX_UNIT_SP, limitSpSize,
                textView.getContext().getResources().getDisplayMetrics())) break;
    }
    return measurePaint.getTextSize();
}
whizzle
  • 2,053
  • 17
  • 21