I\'ve been searching for a way of auto fit a text inside a textview. Through my search I\'ve found many solutions like:
thanks for your solution you are superman! I have implemented your code in derived class of TextView. The code is converted to C# code for Xamarin android. You can easily convert to Java if you need(remove the first constructor for Java).
public class AutoFitTextView : TextView
{
public AutoFitTextView(System.IntPtr javaReference, Android.Runtime.JniHandleOwnership transfer)
: base(javaReference, transfer)
{
}
public AutoFitTextView(Context context)
: base(context)
{
}
public AutoFitTextView(Context context, IAttributeSet attrs)
: base(context, attrs)
{
}
public void ResizeFontSize()
{
int textSize = 50;
int maxHeight = this.Height;
while (GetHeightOfMultiLineText(this.Text, textSize, this.Width) > maxHeight)
{
textSize--;
}
float scaleFactor = Context.Resources.DisplayMetrics.ScaledDensity;
float additionalFactor = 1.2f;
TextSize = ((float)(textSize / (additionalFactor * scaleFactor)));
}
private int GetHeightOfMultiLineText(string text, int textSize, int maxWidth)
{
TextPaint paint = new TextPaint();
paint.TextSize = textSize;
int index = 0;
int lineCount = 0;
while (index < text.Length)
{
index += paint.BreakText(text, index, text.Length, true, maxWidth, null);
lineCount++;
}
Rect bounds = new Rect();
paint.GetTextBounds("Yy", 0, 2, bounds);
// obtain space between lines
double lineSpacing = Math.Max(0, ((lineCount - 1) * bounds.Height() * 0.25));
return (int)Math.Floor(lineSpacing + lineCount * bounds.Height());
}
}
Here is AXML code