0

Depending on the TextView width I want to set the textSize as big as possible so that it does NOT exceed the limits.

The problem in my code is that the calcul seems not correct because the text is too big.

I measured the label width (on a screenshot) with Gimp and the variable textWidthToFit is correct (in my case 298px)

Here my code (My class overrides TextView) :

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
    if (stretchable)
    {
        resizeText();
    }

    super.onSizeChanged(w, h, oldw, oldh);
}

private void resizeText()
{
    if (stretchable && (getText().length() > 0))
    {
        float textWidth=0;
        setTextSize(maxTextSize);
        float newTextSize=getPaint().getTextSize();
        int textWidthToFit = getMeasuredWidth() - getPaddingLeft() - getPaddingRight();
        TextPaint paint = new TextPaint(getPaint());
        String text = getText().toString();

        boolean sizeFound = false;
        while (!sizeFound)
        {
            newTextSize -= 0.5f;

            paint.setTextSize(newTextSize);
            textWidth = paint.measureText(text);

            if (textWidth < textWidthToFit || newTextSize < 5)
            {
                sizeFound = true;
            }

        }

        setTextSize(newTextSize);
    }
}

Thanks.

Lal
  • 14,505
  • 4
  • 39
  • 63
Florian Mac Langlade
  • 1,789
  • 6
  • 26
  • 55

0 Answers0